Find all documents that have two specific id's in an array of objects in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $and operator for this. Let us first create a collection with documents −

> db.twoSpecificIdsDemo.insertOne(
...   {
...      PlayerId:1,
...      "PlayerDetails": [{
...         id: 100,
...         "PlayerName":"Chris"
...      },{
...         id: 101,
...         "PlayerName":"Sam"
...      },{
...         id: 102,
...         "PlayerName":"Robert"
...      },{
...         id: 103,
...         "PlayerName":"Carol"
...      }]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3e130edc6604c74817ce4")
}
> db.twoSpecificIdsDemo.insertOne(
...   {
...      PlayerId:1,
...      "PlayerDetails": [{
...         id: 104,
...         "PlayerName":"Mike"
...      },{
...         id: 105,
...         "PlayerName":"Bob"
...      },{
...         id: 102,
...         "PlayerName":"Ramit"
...      },{
...         id: 106,
...         "PlayerName":"David"
...      }]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3e167edc6604c74817ce5")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.twoSpecificIdsDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3e130edc6604c74817ce4"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 100,
         "PlayerName" : "Chris"
      },
      {
         "id" : 101,
         "PlayerName" : "Sam"
      },
      {
         "id" : 102,
         "PlayerName" : "Robert"
      },
      {
         "id" : 103,
         "PlayerName" : "Carol"
      }
   ]
}
{
   "_id" : ObjectId("5cd3e167edc6604c74817ce5"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 104,
         "PlayerName" : "Mike"
      },
      {
         "id" : 105,
         "PlayerName" : "Bob"
      },
      {
         "id" : 102,
         "PlayerName" : "Ramit"
      },
      {
         "id" : 106,
         "PlayerName" : "David"
      }
   ]
}

Here is the query to find all documents that have two specific id's in an array of objects in MongoDB −

> db.twoSpecificIdsDemo.find( { $and : [ { "PlayerDetails.id" : 102 }, { "PlayerDetails.id" : 103 } ] } ).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3e130edc6604c74817ce4"),
   "PlayerId" : 1,
   "PlayerDetails" : [
      {
         "id" : 100,
         "PlayerName" : "Chris"
      },
      {
         "id" : 101,
         "PlayerName" : "Sam"
      },
      {
         "id" : 102,
         "PlayerName" : "Robert"
      },
      {
         "id" : 103,
         "PlayerName" : "Carol"
      }
   ]
}
raja
Published on 23-May-2019 11:57:02
Advertisements