Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to hide _id from Aggregation?
To hide the _id field from aggregation results in MongoDB, use the $project stage with _id: 0 to exclude it while specifying other fields to include.
Syntax
db.collectionName.aggregate([
{
$project: {
_id: 0,
fieldName1: 1,
fieldName2: 1
}
}
])
Sample Data
Let's create a collection with sample documents ?
db.hideidDemo.insertMany([
{"UserName": "Larry", "UserAge": 23, "UserCountryName": "US"},
{"UserName": "Chris", "UserAge": 21, "UserCountryName": "AUS"},
{"UserName": "Robert", "UserAge": 26, "UserCountryName": "UK"}
])
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c92b02336de59bd9de06392"),
ObjectId("5c92b03036de59bd9de06393"),
ObjectId("5c92b04036de59bd9de06394")
]
}
View all documents to see the data structure ?
db.hideidDemo.find().pretty()
{
"_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"
}
Example: Hide _id and Select Specific Fields
Use aggregation with $project to exclude _id and include only UserName and UserCountryName ?
db.hideidDemo.aggregate([
{
$project: {
_id: 0,
UserName: 1,
UserCountryName: 1
}
}
])
{"UserName": "Larry", "UserCountryName": "US"}
{"UserName": "Chris", "UserCountryName": "AUS"}
{"UserName": "Robert", "UserCountryName": "UK"}
Key Points
- Set
_id: 0in the$projectstage to exclude the_idfield - Use
fieldName: 1to explicitly include other fields - By default,
_idis always included unless explicitly excluded
Conclusion
The $project stage with _id: 0 effectively hides the _id field from aggregation output. This approach gives you clean results containing only the fields you need for your analysis.
Advertisements
