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" } ] }
raja
Published on 14-Jun-2019 14:52:55
Advertisements