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



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 }
Updated on: 2019-07-30T22:30:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements