Get MongoDB documents that contains specific attributes in array

MongoDBDatabaseBig Data Analytics

For this, you can use $and along with dot(.) notation. Let us first create a collection with documents −

>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e08b56e25ddae1f53b62219"),
   "StudentInformation" : [
      {
         "StudentName" : "John",
         "StudentAge" : 21
      },
      {
         "StudentName" : "Mike",
         "StudentAge" : 22
      }
   ]
}
{
   "_id" : ObjectId("5e08b58625ddae1f53b6221a"),
   "StudentInformation" : [
      {
         "StudentName" : "Carol",
         "StudentAge" : 19    
     },    
     {
         "StudentName" : "Bob",
         "StudentAge" : 18
      }
   ]
}

Following is the query to get documents that contains specific attributes in array−

>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});

This will produce the following output −

{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }
raja
Published on 31-Mar-2020 11:58:48
Advertisements