7

I cannot find out of how to check, if some value are in array property in mongo document. For example, I have some collection users, and such document:

{
  'name':'Paul',
  'age':43,
  'friendsIDs': [ ObjectId('qqq...'), ObjectId('www...'), ObjectId('eee...') ],
}

Now let's suppose that I want to check, is user with ID ObjectId('qqq...') a friend of Paul, or not. This is quite easy to do in almost all programming languages, for example in php it would be something like:

$isFriendOfPaul = in_array( ObjectId('qqq...'), $friendsIds );

But how to query this in mongo? Any ideas?

0

3 Answers 3

25

Actually, it is $in the manual.

Sign up to request clarification or add additional context in comments.

4 Comments

show me the query please. It's vice versa of query with $in.
"If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (e.g. <value1>, <value2>, etc.)" -- so it should work both ways. So I guess you could try to get it: db.collection.find({friendsIDs: {$in: [YourIDValue]}})
Nobody even addresses the pun that made me fall over?
badumts tching 🥁😎
3

Your query must be like this:

db.collection.find({"name": "Paul", "friendsIDs": "qqq"}) 

This query finds the document with name Paul and friendsIDs equal to qqq.

3 Comments

'friendsIDs' is a list (array) of Ids, not one ID
This works fine even when friendsIDs is an array.
1

This can also be done with $eq

> db.person.insert({name: 'Paul', age: 43, friends: [1234, 2345, 3456]})
> db.person.insert({name: 'Dave', age: 23, friends: [2345, 3456]})
> db.person.insert({name: 'Stephen', age: 12, friends: [2345, 3456, 7890]})

Below is an example using $eq:

> db.person.find({friends: {$eq : 2345}}) 
{ "_id" : ObjectId("54e34124fe135475834334da"), "name" : "Paul", "age" : 43, "friends" : [ 1234, 2345, 3456 ] }
{ "_id" : ObjectId("54e34138fe135475834334db"), "name" : "Dave", "age" : 23, "friends" : [ 2345, 3456 ] }
{ "_id" : ObjectId("54e3414bfe135475834334dc"), "name" : "Stephen", "age" : 12, "friends" : [ 2345, 3456, 7890 ] }

but the queries below also find the same. So as Sven suggested, you can leave out $eq.

> db.person.find({friends: 2345})
{ "_id" : ObjectId("54e34124fe135475834334da"), "name" : "Paul", "age" : 43, "friends" : [ 1234, 2345, 3456 ] }
{ "_id" : ObjectId("54e34138fe135475834334db"), "name" : "Dave", "age" : 23, "friends" : [ 2345, 3456 ] }
{ "_id" : ObjectId("54e3414bfe135475834334dc"), "name" : "Stephen", "age" : 12, "friends" : [ 2345, 3456, 7890 ] }

> db.person.find({friends: 1234})
{ "_id" : ObjectId("54e34124fe135475834334da"), "name" : "Paul", "age" : 43, "friends" : [ 1234, 2345, 3456 ] }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.