Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to hide _id from Aggregation?
To hide _id from aggregation, use the below syntax −
db.yourCollectionName.aggregate(
{$project : {
_id : 0 ,
yourIncludeFieldName:1,
yourIncludeFieldName:1
}}
).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.hideidDemo.insertOne({"UserName":"Larry","UserAge":23,"UserCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b02336de59bd9de06392")
}
> db.hideidDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b03036de59bd9de06393")
}
> db.hideidDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c92b04036de59bd9de06394")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.hideidDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c92b02336de59bd9de06392"),
"UserName" : "Larry",
"UserAge" : 23,
"UserCountryName" : "US"
}
{
"_id" : ObjectId("5c92b03036de59bd9de06393"),
"UserName" : "Chris",
"UserAge" : 21,
"UserCountryName" : "AUS"
}
{
"_id" : ObjectId("5c92b04036de59bd9de06394"),
"UserName" : "Robert",
"UserAge" : 26,
"UserCountryName" : "UK"
}
Here is the query to hide _id from aggregation −
> db.hideidDemo.aggregate(
... {$project : {
... _id : 0 ,
... UserName:1,
... UserCountryName:1
... }}
... ).pretty();
The following is the output −
{ "UserName" : "Larry", "UserCountryName" : "US" }
{ "UserName" : "Chris", "UserCountryName" : "AUS" }
{ "UserName" : "Robert", "UserCountryName" : "UK" }Advertisements