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 prevent MongoDB from returning the object ID while finding a document?
To prevent MongoDB from returning the Object ID while finding a document, you need to set _id to 0 in the projection parameter of the find() method. This excludes the _id field from the query results.
Syntax
db.collection.find(
{ query },
{ "_id": 0, "field1": 1, "field2": 1 }
);
Sample Data
Let us first create a collection with a sample document ?
db.preventObjectIdDemo.insertOne({
"StudentName": "Chris",
"StudentDetails": [
{
"StudentTotalScore": 540,
"StudentCountryName": "US"
},
{
"StudentTotalScore": 489,
"StudentCountryName": "UK"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ca20a9c66324ffac2a7dc63")
}
Example 1: Default Query (With _id)
First, let's see the default behavior where _id is included ?
db.preventObjectIdDemo.find().pretty();
{
"_id": ObjectId("5ca20a9c66324ffac2a7dc63"),
"StudentName": "Chris",
"StudentDetails": [
{
"StudentTotalScore": 540,
"StudentCountryName": "US"
},
{
"StudentTotalScore": 489,
"StudentCountryName": "UK"
}
]
}
Example 2: Exclude _id Field
Now, let's exclude the _id field by setting it to 0 in the projection ?
db.preventObjectIdDemo.find(
{},
{ "_id": 0 }
).pretty();
{
"StudentName": "Chris",
"StudentDetails": [
{
"StudentTotalScore": 540,
"StudentCountryName": "US"
},
{
"StudentTotalScore": 489,
"StudentCountryName": "UK"
}
]
}
Example 3: Exclude _id with Specific Field Selection
You can also combine _id exclusion with specific field selection ?
db.preventObjectIdDemo.find(
{},
{ "StudentName": 1, "_id": 0 }
).pretty();
{
"StudentName": "Chris"
}
Key Points
- Set
"_id": 0in the projection parameter to exclude the Object ID. - The
_idfield is included by default in all MongoDB queries. - You can combine
_idexclusion with other field projections.
Conclusion
Use {"_id": 0} in the projection parameter of find() to prevent MongoDB from returning the Object ID. This provides cleaner output when the _id field is not needed in your results.
Advertisements
