Can MongoDB find() function display avoiding _id?


Yes, we can avoid the _id, using the following syntax in MongoDB −

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

Let us first create a collection with documents:>

> db.excludeIdDemo.insertOne({"CustomerName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f62c1a844af18acdffb9")
}
> db.excludeIdDemo.insertOne({"CustomerName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f6311a844af18acdffba")
}
> db.excludeIdDemo.insertOne({"CustomerName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f6351a844af18acdffbb")
}
> db.excludeIdDemo.insertOne({"CustomerName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7f6381a844af18acdffbc")
}

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

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

This will produce the following output −

{ "_id" : ObjectId("5cd7f62c1a844af18acdffb9"), "CustomerName" : "Larry" }
{ "_id" : ObjectId("5cd7f6311a844af18acdffba"), "CustomerName" : "Chris" }
{ "_id" : ObjectId("5cd7f6351a844af18acdffbb"), "CustomerName" : "Mike" }
{ "_id" : ObjectId("5cd7f6381a844af18acdffbc"), "CustomerName : "Bob" }

Following is the query to exclude _id in find() −

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

This will produce the following output −

{ "CustomerName" : "Larry" }
{ "CustomerName" : "Chris" }
{ "CustomerName" : "Mike" }
{ "CustomerName" : "Bob" }
raja
Published on 13-Jun-2019 14:34:33
Advertisements