MongoDB query for Partial Object in an array


Let us first create a collection with documents −

> db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":1, "StudentName":"Chris"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfcf55bf3115999ed51206")
}
> db.queryForPartialObjectDemo.insertOne({_id:new ObjectId(), "StudentDetails": [{"StudentId":2, "StudentName":"David"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfcf55bf3115999ed51207")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cdfcf55bf3115999ed51206"),
   "StudentDetails" : [
      {
         "StudentId" : 1,
         "StudentName" : "Chris"
      }
   ]
}
{
   "_id" : ObjectId("5cdfcf55bf3115999ed51207"),
   "StudentDetails" : [
      {
         "StudentId" : 2,
         "StudentName" : "David"
      }
   ]
}

First Approach

Following is the query for partial object in array with MongoDB −

> db.queryForPartialObjectDemo.find({StudentDetails: {StudentId: 1, "StudentName" : "Chris"}});

This will produce the following output −

{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }

Second Approach

Following is the query for partial object in an array with dot notation −

> db.queryForPartialObjectDemo.find({"StudentDetails.StudentName":"Chris"});

This will produce the following output −

{ "_id" : ObjectId("5cdfcf55bf3115999ed51206"), "StudentDetails" : [ { "StudentId" : 1, "StudentName" : "Chris" } ] }

Updated on: 30-Jul-2019

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements