質問

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?

役に立ちましたか?

解決

Actually, it is $in the manual.

他のヒント

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.

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 ] }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top