Retrieving a Subset of Fields from MongoDB


To retried a subset of fields, use dot notation in find(). Let us create a collection with documents −

> db.demo307.insertOne({
...   "CleintId":101,
...   "ClientDetails":{"ClientFirstName":"Chris","Age":34},
...   "ClientCountryName":"US"
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4eab88f8647eb59e56203c")
}
> db.demo307.insertOne({
...   "CleintId":102,
...   "ClientDetails":{"ClientFirstName":"David","Age":31},
...   "ClientCountryName":"UK"
...}
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4eab97f8647eb59e56203d")
}

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

>  db.demo307.find();

This will produce the following output −

{ "_id" : ObjectId("5e4eab88f8647eb59e56203c"), "CleintId" : 101, "ClientDetails" : { "ClientFirstName" : "Chris", "Age" : 34 }, "ClientCountryName" : "US" }
{ "_id" : ObjectId("5e4eab97f8647eb59e56203d"), "CleintId" : 102, "ClientDetails" : { "ClientFirstName" : "David", "Age" : 31 }, "ClientCountryName" : "UK" }

Following is the query to retrieve a subset of fields from MongoDB −

> db.demo307.find( {"ClientDetails.ClientFirstName":'David'}, {"ClientDetails.Age" : 0,"ClientCountryName":0,CleintId:0,_id:0});

This will produce the following output −

{ "ClientDetails" : { "ClientFirstName" : "David" } }

Updated on: 01-Apr-2020

476 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements