Display only a single field from all the documents in a MongoDB collection

MongoDBDatabaseBig Data Analytics

Projection means only selected field must be visible. Set the field to 1, if you want to make it visible.

Let us first create a collection with documents −

> db.demo384.insertOne({"StudentName":"Chris Brown","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67a022064be7ab44e7f2")
}
> db.demo384.insertOne({"StudentName":"David Miller","StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67ab22064be7ab44e7f3")
}
> db.demo384.insertOne({"StudentName":"John Doe","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5b67b422064be7ab44e7f4")
}

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

> db.demo384.find();

This will produce the following output −

{ "_id" : ObjectId("5e5b67a022064be7ab44e7f2"), "StudentName" : "Chris Brown", "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e5b67ab22064be7ab44e7f3"), "StudentName" : "David Miller", "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5e5b67b422064be7ab44e7f4"), "StudentName" : "John Doe", "StudentCountryName" : "UK" }

Following is the query to display only a single field and ignore rest of them −

> db.demo384.find({},{_id:0,StudentName:0});

This will produce the following output −

{ "StudentCountryName" : "US" }
{ "StudentCountryName" : "AUS" }
{ "StudentCountryName" : "UK" }
raja
Published on 02-Apr-2020 17:12:56
Advertisements