MongoDB query to display all the values excluding the id?


For this, use the $project. The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields

Let us first create a collection with documents −

> db.demo226.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3f9be803d395bdc2134738")
}
> db.demo226.insertOne({"Name":"Bob","Age":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3f9bf003d395bdc2134739")
}
> db.demo226.insertOne({"Name":"David","Age":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3f9bf803d395bdc213473a")
}

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

> db.demo226.find();

This will produce the following output −

{ "_id" : ObjectId("5e3f9be803d395bdc2134738"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e3f9bf003d395bdc2134739"), "Name" : "Bob", "Age" : 20 }
{ "_id" : ObjectId("5e3f9bf803d395bdc213473a"), "Name" : "David", "Age" : 22 }

Following is the query to display all the values excluding id −

> db.demo226.aggregate(
...   {$project:
...      {
...         _id: false,
..."         StudentFirstName":"$Name",
...         "StudentAge":"$Age"
...      }
...   }
...);

This will produce the following output −

{ "StudentFirstName" : "Chris", "StudentAge" : 21 }
{ "StudentFirstName" : "Bob", "StudentAge" : 20 }
{ "StudentFirstName" : "David", "StudentAge" : 22 }

Updated on: 30-Mar-2020

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements