Query a nested field within an array with MongoDB


To query a nested field within an array, use $elemMatch in MongoDB. Let us create a collection with documents −

> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Chris","ClientProject":"Online Banking System"},{"ClientName":"David","ClientProject":"Online School Management"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e351957fdf09dd6d08539df")
}
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Carol","ClientProject":"Online Book System"},{"ClientName":"Mike","ClientProject":"Game Development"}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0")
}

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

> db.demo153.find();

This will produce the following output −

{
   "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [
      { "ClientName" : "Chris", "ClientProject" : "Online Banking System" },
      { "ClientName" : "David", "ClientProject" : "Online School Management" }
   ]
}
{
   "_id" : ObjectId("5e3519c9fdf09dd6d08539e0"), "ClientDetails" : [
      { "ClientName" : "Carol", "ClientProject" : "Online Book System" },
      { "ClientName" : "Mike", "ClientProject" : "Game Development" }
   ]
}

Following is how to query a nested field within an array −

> db.demo153.find({"ClientDetails": { "$elemMatch" : {"ClientProject": { "$in": ["Online Banking System"] } } } });

This will produce the following output −

{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }

Updated on: 01-Apr-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements