Reputation: 937
Hello I've got a mongodb find() question query. I am trying to find all documents that have two specific id's in the same array of objects.
Sample Document Structure:
doc 1
{
gameId:394028,
people: [{
id: 5,
mapSide: 'left'
},{
id: 4,
mapSide: 'right'
},{
id: 1,
mapSide: 'right'
},{
id: 2,
mapSide: 'left'
}]
}
doc 2
{
gameId:394028,
people: [{
id: 7,
mapSide: 'left'
},{
id: 9,
mapSide: 'right'
},{
id: 4,
mapSide: 'right'
},{
id: 1,
mapSide: 'left'
}]
}
How would I go about getting all documents that have an id of 5 and 4 in the same people array? I've tried this shell command:
db.COLLECTION.find({"people.id":5, "people.id":4}); //should return doc 1
However I am yet to get any results. I also intend to find the id only if they have a different map side - I've tried this:
db.COLLECTION.find({
people: {$elemMatch:{id:4, mapSide:"left"},
people: {$elemMatch:{id:1, mapSide:"right"}
},{
people: {$elemMatch:{id:4, mapSide:"right"},
people: {$elemMatch:{id:1, mapSide:"left"}
}); //Should return doc 2, because doc 1 has both mapSide as 'right'
If I could have a hand for either of those questions, that would be great! Thanks.
Upvotes: 4
Views: 1844
Reputation: 19480
You can use the following query to find all documents where the people
array contains both an element with id == 4
and an element with id == 5
:
db.COLLECTION.find( { $and : [ { 'people.id' : 4 }, { 'people.id' : 5 } ] } )
Upvotes: 5