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
Can MongoDB find() function display avoiding _id?
Yes, MongoDB find() function can display results while excluding the _id field by using projection. Set _id: 0 in the projection parameter to hide it from the output.
Syntax
db.collectionName.find({}, { _id: 0 });
Sample Data
Let us first create a collection with sample documents ?
db.excludeIdDemo.insertMany([
{ "CustomerName": "Larry" },
{ "CustomerName": "Chris" },
{ "CustomerName": "Mike" },
{ "CustomerName": "Bob" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7f62c1a844af18acdffb9"),
ObjectId("5cd7f6311a844af18acdffba"),
ObjectId("5cd7f6351a844af18acdffbb"),
ObjectId("5cd7f6381a844af18acdffbc")
]
}
Example 1: Default find() with _id
Display all documents using the default find() method ?
db.excludeIdDemo.find();
{ "_id": ObjectId("5cd7f62c1a844af18acdffb9"), "CustomerName": "Larry" }
{ "_id": ObjectId("5cd7f6311a844af18acdffba"), "CustomerName": "Chris" }
{ "_id": ObjectId("5cd7f6351a844af18acdffbb"), "CustomerName": "Mike" }
{ "_id": ObjectId("5cd7f6381a844af18acdffbc"), "CustomerName": "Bob" }
Example 2: Exclude _id from Results
Use projection to exclude the _id field from the output ?
db.excludeIdDemo.find({}, { _id: 0 });
{ "CustomerName": "Larry" }
{ "CustomerName": "Chris" }
{ "CustomerName": "Mike" }
{ "CustomerName": "Bob" }
Key Points
- The
_idfield is included by default in all MongoDB query results. - Use
{ _id: 0 }in the projection parameter to exclude it. - You can combine
_id: 0with other field projections for selective output.
Conclusion
MongoDB find() excludes the _id field by setting _id: 0 in the projection parameter. This is useful when you only need the actual data fields without the auto-generated identifier.
Advertisements
