How to prevent MongoDB from returning the object ID while finding a document?


To prevent MongoDB from returning the Object ID while finding a document, you need to set _id to 0. Let us first create a collection with documents

> db.preventObjectIdDemo.insertOne(
...    {
...
...       "StudentName" : "Chris",
...       "StudentDetails" : [
...          {
...             "StudentTotalScore" : 540,
...             "StudentCountryName" : "US"
...          },
...          {
...             "StudentTotalScore" : 489,
...             "StudentCountryName" : "UK"
...          }
...       ]
...    }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca20a9c66324ffac2a7dc63")
}

Following is the query to display all documents from a collection with the help of find() method

> db.preventObjectIdDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5ca20a9c66324ffac2a7dc63"),
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      },
      {
         "StudentTotalScore" : 489,
         "StudentCountryName" : "UK"
      }
   ]
}

Following is the query to prevent MongoDB from returning the Object ID when finding a document

> db.preventObjectIdDemo.find({ _id: ObjectId("5ca20a9c66324ffac2a7dc63")},
{StudentDetails: { $slice: [0, 1] } ,'_id': 0} ).pretty();

The following is the output where ObjectID isn’t visible

{
   "StudentName" : "Chris",
   "StudentDetails" : [
      {
         "StudentTotalScore" : 540,
         "StudentCountryName" : "US"
      }
   ]
}

Updated on: 30-Jul-2019

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements