Projection of one column in MongoDB?


Let us first create a collection with documents −

> db.demo216.insertOne({"ClientName":"John","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e351003d395bdc213470c")
}
> db.demo216.insertOne({"ClientName":"Bob","ClientAge":32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e351703d395bdc213470d")
}
> db.demo216.insertOne({"ClientName":"Mike","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e351c03d395bdc213470e")
}

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

> db.demo216.find();

This will produce the following output −

{ "_id" : ObjectId("5e3e351003d395bdc213470c"), "ClientName" : "John", "ClientAge" : 34 }
{ "_id" : ObjectId("5e3e351703d395bdc213470d"), "ClientName" : "Bob", "ClientAge" : 32 }
{ "_id" : ObjectId("5e3e351c03d395bdc213470e"), "ClientName" : "Mike", "ClientAge" : 35 }

Following is the query to project only a single column −

> db.demo216.find({},{_id:0,"ClientAge":0});

This will produce the following output −

{ "ClientName" : "John" }
{ "ClientName" : "Bob" }
{ "ClientName" : "Mike" }

Updated on: 30-Mar-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements