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 exclude _id without including other fields using the aggregation framework in MongoDB?
To exclude the _id field without explicitly including other fields in MongoDB's aggregation framework, use the $project stage with _id: 0 and selectively include only the fields you need.
Syntax
db.collection.aggregate([
{
$project: {
_id: 0,
"field1": 1,
"field2": 1
}
}
]);
Sample Data
db.excludeIdDemo.insertMany([
{"StudentFirstName": "John", "StudentAge": 21},
{"StudentFirstName": "Robert", "StudentAge": 20},
{"StudentFirstName": "Chris", "StudentAge": 24}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd701a56d78f205348bc632"),
ObjectId("5cd701af6d78f205348bc633"),
ObjectId("5cd701b86d78f205348bc634")
]
}
Display All Documents
db.excludeIdDemo.find();
{ "_id" : ObjectId("5cd701a56d78f205348bc632"), "StudentFirstName" : "John", "StudentAge" : 21 }
{ "_id" : ObjectId("5cd701af6d78f205348bc633"), "StudentFirstName" : "Robert", "StudentAge" : 20 }
{ "_id" : ObjectId("5cd701b86d78f205348bc634"), "StudentFirstName" : "Chris", "StudentAge" : 24 }
Example: Exclude _id and Include Specific Fields
To exclude _id and show only StudentFirstName ?
db.excludeIdDemo.aggregate([
{
$project: {
_id: 0,
"StudentFirstName": 1
}
}
]);
{ "StudentFirstName" : "John" }
{ "StudentFirstName" : "Robert" }
{ "StudentFirstName" : "Chris" }
Key Points
- Set
_id: 0to exclude the_idfield from the output. - Use
fieldName: 1to explicitly include specific fields. - In
$project, you must either include fields (1) or exclude them (0), but not mix both except for_id.
Conclusion
The $project stage with _id: 0 effectively excludes the _id field while allowing selective inclusion of other fields. This approach gives you precise control over the output structure in aggregation pipelines.
Advertisements
