Select Specific Columns in MongoDB Query



To select specific columns, you can ignore the rest of them i.e. to hide those columns, set them to 0. Let us first create a collection with documents −

> db.demo415.insertOne({"ClientName":"Robert","ClientCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e72329db912067e57771adc")
}
> db.demo415.insertOne({"ClientName":"David","ClientCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7232acb912067e57771add")
}
> db.demo415.insertOne({"ClientName":"Bob","ClientCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7232b4b912067e57771ade")
}

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

> db.demo415.find();

This will produce the following output −

{ "_id" : ObjectId("5e72329db912067e57771adc"), "ClientName" : "Robert", "ClientCountryName" : "US" }
{ "_id" : ObjectId("5e7232acb912067e57771add"), "ClientName" : "David", "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5e7232b4b912067e57771ade"), "ClientName" : "Bob", "ClientCountryName" : "AUS" }

Following is the query to select specific columns. Here, we have ignored rest of the columns to display the column “ClientCountryName” −

> db.demo415.find({},{_id:0,ClientName:0});

This will produce the following output −

{ "ClientCountryName" : "US" }
{ "ClientCountryName" : "UK" }
{ "ClientCountryName" : "AUS" }
Updated on: 2020-04-03T13:28:16+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements