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 return documents of a collection without objectId in MongoDB?
To return documents of a collection without objectId in MongoDB, use projection with _id:0 in the find() method. This excludes the automatically generated _id field from the query results.
Syntax
db.collection.find(query, { _id: 0 });
Sample Data
db.returnDocumentWithoutObjectId.insertMany([
{ "Name": "Carol", "Age": 25 },
{ "Name": "Sam", "Age": 21 },
{ "Name": "John", "Age": 23 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ce8ba6c78f00858fb12e8fa"),
ObjectId("5ce8ba6d78f00858fb12e8fb"),
ObjectId("5ce8ba6f78f00858fb12e8fc")
]
}
Example 1: Default Query (With ObjectId)
First, let's see how documents appear with the default _id field ?
db.returnDocumentWithoutObjectId.find();
{ "_id": ObjectId("5ce8ba6c78f00858fb12e8fa"), "Name": "Carol", "Age": 25 }
{ "_id": ObjectId("5ce8ba6d78f00858fb12e8fb"), "Name": "Sam", "Age": 21 }
{ "_id": ObjectId("5ce8ba6f78f00858fb12e8fc"), "Name": "John", "Age": 23 }
Example 2: Exclude ObjectId
Now exclude the _id field using projection ?
db.returnDocumentWithoutObjectId.find({}, { _id: 0 });
{ "Name": "Carol", "Age": 25 }
{ "Name": "Sam", "Age": 21 }
{ "Name": "John", "Age": 23 }
Key Points
- The
_idfield is automatically included in all MongoDB queries by default. - Use
{ _id: 0 }as the second parameter (projection) to exclude it. - You can combine this with other field projections to control which fields are returned.
Conclusion
Use projection with _id: 0 in the find() method to return documents without the ObjectId field. This provides cleaner output when the _id field is not needed for your application logic.
Advertisements
