Find all documents that have two specific IDs in an array of objects. MongoDB

Hi I have a mongodb find () query question. I am trying to find all documents that have two specific IDs in the same array of objects.

Example of 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 can I get all documents with ID 5 and 4 in one people array? I tried this shell command:

    db.COLLECTION.find({"people.id":5, "people.id":4}); //should return doc 1

      

However, I have not received any results yet. I also intend to only find the id if they have the other side of the map - 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 had a hand for any of these questions, that would be great! Thank.

+3


source to share


1 answer


You can use the following query to find all documents where the array people

contains both element c id == 4

and element c id == 5

:



db.COLLECTION.find( { $and : [ { 'people.id' : 4 }, { 'people.id' : 5 } ] } )

      

+3


source







All Articles