Query a nested field within an array with MongoDB

MongoDBDatabaseBig Data Analytics

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" } ] }
raja
Published on 01-Apr-2020 14:35:58
Advertisements