How to get the child of a MongoDB collection by the key?

MongoDBDatabaseBig Data Analytics

To get the child of a collection in MongoDB, use find(). Let us create a collection with documents −

> db.demo305.insertOne(
...   {
...      _id: 101,
...      FirstName : 'Chris',
...      details : {
...         "0":"102",
...         "1":"10001"
...      }
...   }
...);
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo305.insertOne(
...   {
...      _id: 102,
...      FirstName : 'David',
...      details : {
...         "0":"103",
...         "1":"10002"
...      }
...   }
...);
{ "acknowledged" : true, "insertedId" : 102 }

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

> db.demo305.find();

This will produce the following output −

{ "_id" : 101, "FirstName" : "Chris", "details" : { "0" : "102", "1" : "10001" } }
{ "_id" : 102, "FirstName" : "David", "details" : { "0" : "103", "1" : "10002" } }

Following is the query to get the child of a MongoDB collection by the key −

> db.demo305.find({_id:102},{'details.0':1});

This will produce the following output −

{ "_id" : 102, "details" : { "0" : "103" } }
raja
Published on 01-Apr-2020 07:34:10
Advertisements