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
MongoDB query to display all the values excluding the id?
To exclude the _id field from MongoDB query results, use the $project operator in an aggregation pipeline. The $project stage allows you to include or exclude fields, suppress the _id field, and rename existing fields.
Syntax
db.collection.aggregate([
{ $project: { _id: 0, field1: 1, field2: 1 } }
]);
Sample Data
db.demo226.insertMany([
{ "Name": "Chris", "Age": 21 },
{ "Name": "Bob", "Age": 20 },
{ "Name": "David", "Age": 22 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3f9be803d395bdc2134738"),
ObjectId("5e3f9bf003d395bdc2134739"),
ObjectId("5e3f9bf803d395bdc213473a")
]
}
Display All Documents (with _id)
db.demo226.find();
{ "_id": ObjectId("5e3f9be803d395bdc2134738"), "Name": "Chris", "Age": 21 }
{ "_id": ObjectId("5e3f9bf003d395bdc2134739"), "Name": "Bob", "Age": 20 }
{ "_id": ObjectId("5e3f9bf803d395bdc213473a"), "Name": "David", "Age": 22 }
Method 1: Exclude _id Using $project
db.demo226.aggregate([
{ $project: {
_id: false,
"StudentFirstName": "$Name",
"StudentAge": "$Age"
}}
]);
{ "StudentFirstName": "Chris", "StudentAge": 21 }
{ "StudentFirstName": "Bob", "StudentAge": 20 }
{ "StudentFirstName": "David", "StudentAge": 22 }
Method 2: Using find() with Projection
db.demo226.find({}, { _id: 0, Name: 1, Age: 1 });
{ "Name": "Chris", "Age": 21 }
{ "Name": "Bob", "Age": 20 }
{ "Name": "David", "Age": 22 }
Key Points
- Set
_id: falseor_id: 0to exclude the _id field from results. - Use
$projectin aggregation for field renaming and transformation. - Use
find()projection for simple field inclusion/exclusion.
Conclusion
Use $project with _id: false in aggregation pipelines or projection parameters in find() to exclude the _id field from MongoDB query results. The aggregation approach also allows field renaming and transformation.
Advertisements
