How to user $in query in mongodb? - mongodb

I want to fetch records when permission = User.
Below is my colletions:
"_id":ObjectId("59177f050c9db20629f4562"),
"profile":
{
"permissionGroups" : [
"Admin",
"Restaurant",
"Salesperson",
"User"
]
}
Fetch only in permission is User.
Thanks in advance,

Well first, access the permissionGroups array inside profile obj and then run a query simply matching the string like this. You don't need to run a $in unless you have multiple strings in array to match with:
db.getCollection('collection name').find({"profile.permissionGroups" : "User"})

I don't think $in is what you're looking for. $in queries an array against a field, so let's say you search permissionsGroup: {$in: ['User', 'Admin']}, and that would return all records that could find either User or Admin.
In this case you can simply search for permissionsGroups: 'User'. Mongo is smart enough to recognize permissionGroups as an array, and test the given value against the fields in that array.

Related

How can I query whether each element inside an array match a collection field

I am using mongodb to save user information. There is a userId field in that collection. I get many userIds in my application and saved as an array. I need to query whether all the userIds in that array exist in the collection. If not, find out all the missing ones. Is there one query command does the work? I don't want to query the userId one by one. So what is the better way to achieve this?
The user collection is very simple as below and there is no nested data.
userId: String
name: String
gender: String
phone: String
For example, I have an array of ids [1, 2, 3]. I have to run query three times to check whether these are users to match the three ids.
This can be done with the $in operator.
Example:
db.users.find( {userId: { $in: [ 1, 2, 3 ] } } );
Once you have the users pulled back from that you can determine in the application layer which users did not come back.

Using "$and" and "$in" together

I have a collection friends which i am using to store all the friends and has the following fields
id , userid, friendid
I have a collection notes which stores user notes and has the following fields
id, userid , ownerid , privateorpublic
The rule is a user can only see notes he/she has created or notes created by his/her friends or notes that are public
To fetch that information i am writing my query this way. First, get all the ids of my friends separated by a comma. I dont know how to write the query to return comma delimited values but this query below I am hoping will return all the firneds of the user by the given id:
db.friends.find({ { friendid: { userid: 'jhdshh37838gsjj' } }
then get the notes where are either created by a friend or are public notes or are notes belonging to user
db.notes.find({ownerid:'jhdshh37838gsjj', privateorpublic:'public',{ $in: [ "3ghd8e833", "78hhyaysgd" ] }
I am new to MongoDB. Are my queries right?
Find query syntax : db.collection.find({queryFieldName: queryFieldValue}, {requiredFieldName: 1, NotRequiredFieldName: 0})
Thus, translating first query, you'd get "get me all documents from collection friends where friendId equals a string {'userId':'Id'}" which is not desired.
Query for "Get me all friend Ids of userid jhdshh37838gsjj and don't print anything else in results" : db.collection.find({userId:'jhdshh37838gsjj'}, {friendId:1, _id:0})
However, this'll not give output as comma separated values. You'll get output as follows (because every document is an independent object):
{friendId: 1}
{friendId: 2}
$in requires array as input and not comma separated values. To make an array of field values for a $in query, you need to some extra work like:
var friendIdsArr = [] //Initiate an array to store friend Ids
db.friends.find({'userId':'jhdshh37838gsjj'},{'friendId':1,'_id':0}).forEach(function(x) {friendIdsArr.push(x.friendId);} ); //Foreach result in query, push value to array.
The friendIdsArr will be [1,2]
db.notes.find({'ownerId':'jhdshh37838gsjj', 'privateOrPublic':'public',{$in: ["friendId": friendIdsArr]})
will give results, json documents, matching the given conditions.
Interestingly, your notes collection doesn't have a note field.
I'd recommend you to read mongodb official documentation and make a single query instead of two different queries.

How can I query for a subdocument full of objects in Mongo?

So I have a document with an unknown number of objects in it, each with 2 properties. It's a collection of friend lists, and I'm trying to confirm if someone has a friend with a certain username before I allow a user to send a request. I'm keeping the list of friends in a subdocument, like this:
>>all the _id and other properties<<, "ownerFriends":[{"friendId":"an id goes here", "friendUsername": "username"}, {"friendId":"another id", "friendUsername":"username2"}]
I'm trying to do a query that will return username2 if given that as input, but I don't know how to do that with dot notation because I think you need to know the specific property to look for, and these are heterodox amounts of friend objects in the ownerFriends property.
If you want to select the ownerFriend object that has username as the friendUserName you can use the following selector (assuming your collection is called Friends):
Friends.find({
"ownerFriends.friendUsername": "username2"
}, {
fields: { "ownerFriends.$": 1}
});
You can find a detailed explanation of how to query an array of objects based on a property here:
http://www.curtismlarson.com/blog/2015/08/08/meteor-mongodb-array-property-selector/
In summary you have an object that contains keys, one of whose values is an array of objects. You can perform queries on the arrays using $elemMatch In your case:
MyCollection.find({ ownerFriends: { $elemMatch: { friendUsername: searchString }}});
Although I think you'll need to also query on the current user's _id. Not knowing the details of your collection, I can only speculate with:
MyCollection.find({ userId: Meteor.userId(), ownerFriends: { $elemMatch: { friendUsername: searchString }}});

How to I ensure that all items in an $in clause return a match in MongoDB?

I am working with a set of documents like this:
{
name : "BCC 204",
//etc
}
I have a list of names that I want to map to their DB entries.
For example:
var names = [ "BCC 204", "STEW 101", "SMTH 123" ]
and I want to make a query like this
db.labs.find( { name : { $in: names } } );
But the $in operator does not ensure that each item in the names array matches a result in the db.
(More info, names are unique)
You can't do this in the query. $in will check that a document matches at least one entry in the array given, but it's not going to consider the entire result set. This is a concern you'll need to manage in your application. Given a list of inputs, you will need to retrieve your results then check that given_names - results.map(:name) is empty.
To put it more simply, queries match documents, which compose a result set - they don't match a result set.

How to Retrieve any element value from mongoDB?

Suppose I have following collection :
{ _id" : ObjectId("4f1d8132595bb0e4830d15cc"),
"Data" : "[
{ "id1": "100002997235643", "from": {"name": "Joannah" ,"id": "100002997235643"} , "label" : "test" } ,
{ "id1": "100002997235644", "from": {"name": "Jon" ,"id": "100002997235644"} , "label" : "test1" }
]" ,
"stat" : "true"
}
How can I retrieve id1 , name , id ,label or any other element?
I am able to get _id field , DATA (complete array) but not the inner elements in DATA.
You cannot query for embedded structures. You always query for top level documents. If you want to query for individual elements from your array you will have to make those element top level documents (so, put them in their own collection) and maintain an array of _ids in this document.
That said, unless the array becomes very large it's almost always more efficient to simply grab your entire document and find the appropriate element in your app.
I don't think you can do that. It is explained here.
If you want to access specific fields, then following MongoDB Documentation,
you could add a flag parameter to your query, but you should redesign your documents for this to be useful:
Field Selection
In addition to the query expression, MongoDB queries can take some additional arguments. For example, it's possible to request only certain fields be returned. If we just wanted the social security numbers of users with the last name of 'Smith,' then from the shell we could issue this query:
// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});
// retrieve all fields *except* the thumbnail field, for all documents:
db.users.find({}, {thumbnail:0});