Tutorialspoint

How to return documents of a collection without objectId in MongoDB?


1 Answer
Smita Kapse

To return documents of a collection without objectId, set _id:0. Let us first create a collection with documents −

> db.returnDocumentWithoutObjectId.insertOne({"Name":"Carol","Age":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6c78f00858fb12e8fa")
}
> db.returnDocumentWithoutObjectId.insertOne({"Name":"Sam","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6d78f00858fb12e8fb")
}
> db.returnDocumentWithoutObjectId.insertOne({"Name":"John","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8ba6f78f00858fb12e8fc")
}

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

> db.returnDocumentWithoutObjectId.find();

This will produce the following output −

{ "_id" : ObjectId("5ce8ba6c78f00858fb12e8fa"), "Name" : "Carol", "Age" : 25 }
{ "_id" : ObjectId("5ce8ba6d78f00858fb12e8fb"), "Name" : "Sam", "Age" : 21 }
{ "_id" : ObjectId("5ce8ba6f78f00858fb12e8fc"), "Name" : "John", "Age" : 23 }

Following is the query to return documents of a collection without objectId in MongoDB −

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

This will produce the following output −

{ "Name" : "Carol", "Age" : 25 }
{ "Name" : "Sam", "Age" : 21 }
{ "Name" : "John", "Age" : 23 }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.