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
Hide id field in MongoDB
To hide the _id field in MongoDB query results, use the projection parameter in the find() method and set _id: 0. This excludes the _id field from the output while displaying other specified fields.
Syntax
db.collection.find(
{ query },
{ _id: 0, "field1": 1, "field2": 1 }
);
Sample Data
db.demo575.insertMany([
{id: 101, Information: {Name: "Chris", Age: 21}},
{id: 102, Information: {Name: "David", Age: 20}},
{id: 101, Information: {Name: "Bob", Age: 23}}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e916a55581e9acd78b427f7"),
ObjectId("5e916a5f581e9acd78b427f8"),
ObjectId("5e916a67581e9acd78b427f9")
]
}
Example 1: Display All Fields with _id
db.demo575.find();
{ "_id": ObjectId("5e916a55581e9acd78b427f7"), "id": 101, "Information": { "Name": "Chris", "Age": 21 } }
{ "_id": ObjectId("5e916a5f581e9acd78b427f8"), "id": 102, "Information": { "Name": "David", "Age": 20 } }
{ "_id": ObjectId("5e916a67581e9acd78b427f9"), "id": 101, "Information": { "Name": "Bob", "Age": 23 } }
Example 2: Hide _id Field and Show Specific Fields
db.demo575.find(
{id: 101},
{_id: 0, "Information.Name": 1}
);
{ "Information": { "Name": "Chris" } }
{ "Information": { "Name": "Bob" } }
Key Points
- Use
_id: 0in the projection to exclude the _id field from results. - Combine with
fieldName: 1to include only specific fields you want to see. - The _id field is included by default in all MongoDB queries unless explicitly excluded.
Conclusion
Set _id: 0 in the projection parameter to hide the _id field from MongoDB query results. This provides cleaner output when you only need specific document fields without the auto-generated ObjectId.
Advertisements
