Query deeply nested Objects in MongoDB

MongoDBDatabaseBig Data Analytics

To query deeply nested objects, use dot(.) notation in MongoDB. Let us create a collection with documents −

> db.demo350.insertOne(
... {
...    id:101,
...    Name: "Chris",
...    details: [
...       {
...          _id: 1,
...          ClientNumber: "10001",
...          ClientDetails: [
.
...             {
...                Name:"David",
...                Age:29
...             },
...             {
...                Name:"Bob",
...                Age:31
...             }
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e553a68f8647eb59e5620b8")
}
> db.demo350.insertOne(
... {
...    id:102,
...    Name: "David",
...    details: [
...       {
...          _id: 2,
...          ClientNumber: "10002",
...          ClientDetails: [
...             {
...                Name:"Carol",
...                Age:42
...             },
...             {
...                Name:"John",
...                Age:37
...             }
...          ]
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e553a8ff8647eb59e5620b9")
}

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

> db.demo350.find();

This will produce the following output −

{ "_id" : ObjectId("5e553a68f8647eb59e5620b8"), "id" : 101, "Name" : "Chris", "details" : [ { "_id" : 1, "ClientNumber" : "10001", "ClientDetails" : [ { "Name" : "David", "Age" : 29 }, { "Name" : "Bob", "Age" : 31 } ] } ] }
{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }

Following is how to query deeply nested objects −

> db.demo350.find({"details.ClientDetails.Name":"John"});

This will produce the following output −

{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
raja
Published on 02-Apr-2020 11:25:22
Advertisements