6

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?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
Void Floyd
  • 161
  • 1
  • 1
  • 11

3 Answers3

22

Actually, it is $in the manual.

guessimtoolate
  • 8,372
  • 2
  • 18
  • 26
  • show me the query please. It's vice versa of query with $in. – Void Floyd Apr 15 '13 at 12:12
  • 1
    "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. , , etc.)" -- so it should work both ways. So I guess you could try to get it: `db.collection.find({friendsIDs: {$in: [YourIDValue]}})` – guessimtoolate Apr 15 '13 at 12:20
  • 1
    Nobody even addresses the pun that made me fall over? – Nebulosar Jan 25 '23 at 15:32
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.

YasirA
  • 9,531
  • 2
  • 40
  • 61
SVen
  • 51
  • 2
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 ] }
Sean McClory
  • 4,195
  • 3
  • 32
  • 35