To remove _id from MongoDB result, you need to set 0 for _id field. Following is the syntax
db.yourCollectionName.find({},{_id:0});To understand it, let us create a collection with documents. Following is the query
> db.removeIdDemo.insertOne({"UserName":"John","UserAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb4042d66697741252440")
}
> db.removeIdDemo.insertOne({"UserName":"Mike","UserAge":27});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb40c2d66697741252441")
}
> db.removeIdDemo.insertOne({"UserName":"Sam","UserAge":34});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb4162d66697741252442")
}
> db.removeIdDemo.insertOne({"UserName":"Carol","UserAge":29});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb4222d66697741252443")
}Following is the query to display all documents from a collection with the help of find() method
> db.removeIdDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9bb4042d66697741252440"),
"UserName" : "John",
"UserAge" : 23
}
{
"_id" : ObjectId("5c9bb40c2d66697741252441"),
"UserName" : "Mike",
"UserAge" : 27
}
{
"_id" : ObjectId("5c9bb4162d66697741252442"),
"UserName" : "Sam",
"UserAge" : 34
}
{
"_id" : ObjectId("5c9bb4222d66697741252443"),
"UserName" : "Carol",
"UserAge" : 29
}Following is the query to remove _id from Mongo result
> db.removeIdDemo.find({},{_id:0});This will produce the following output
{ "UserName" : "John", "UserAge" : 23 }
{ "UserName" : "Mike", "UserAge" : 27 }
{ "UserName" : "Sam", "UserAge" : 34 }
{ "UserName" : "Carol", "UserAge" : 29 }