Get array items inside a MongoDB document?

MongoDBDatabaseBig Data Analytics

To get array items in a MongoDB document, use the dot(.) notation. Let us create a collection with documents −

> db.demo29.insertOne({"StudentDetails":[{"StudentName":"Chris","StudentMarks":58},{"StudentName":"Bob","StudentMarks":69}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15fcc08f2315c2efc48e6e")
}
>db.demo29.insertOne({"StudentDetails":[{"StudentName":"David","StudentMarks":97},{"StudentName":"Carol","StudentMarks":96}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e15fcd38f2315c2efc48e6f")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e15fcc08f2315c2efc48e6e"),
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentMarks" : 58
      },
      {
         "StudentName" : "Bob",
         "StudentMarks" : 69
      }
   ]
}
{
   "_id" : ObjectId("5e15fcd38f2315c2efc48e6f"),
   "StudentDetails" : [
      {
         "StudentName" : "David",
         "StudentMarks" : 97
      },
      {
         "StudentName" : "Carol",
         "StudentMarks" : 96
      }
   ]
}

Following is the query to get array items inside a MongoDB document −

> db.demo29.find({"StudentDetails.StudentName":"David"});

This will produce the following output −

{ "_id" : ObjectId("5e15fcd38f2315c2efc48e6f"), "StudentDetails" : [ { "StudentName" : "David", "StudentMarks" : 97 }, { "StudentName" : "Carol", "StudentMarks" : 96 } ] }
raja
Published on 02-Apr-2020 16:02:00
Advertisements