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 remove primary key from MongoDB?
To remove the primary key (_id field) from query results in MongoDB, use projection with the _id: 0 option in the find() method. This excludes the _id field from the returned documents without deleting it from the database.
Syntax
db.collection.find({}, {_id: 0});
db.collection.find({}, {_id: 0, field1: 1, field2: 1});
Sample Data
db.demo471.insertMany([
{"ClientId": 101, "ClientName": "Chris"},
{"ClientId": 102, "ClientName": "Bob"},
{"ClientId": 103, "ClientName": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e805711b0f3fa88e2279077"),
ObjectId("5e80571db0f3fa88e2279078"),
ObjectId("5e805724b0f3fa88e2279079")
]
}
View Default Documents
Display all documents with the default _id field ?
db.demo471.find();
{ "_id": ObjectId("5e805711b0f3fa88e2279077"), "ClientId": 101, "ClientName": "Chris" }
{ "_id": ObjectId("5e80571db0f3fa88e2279078"), "ClientId": 102, "ClientName": "Bob" }
{ "_id": ObjectId("5e805724b0f3fa88e2279079"), "ClientId": 103, "ClientName": "David" }
Method 1: Exclude Only _id Field
Remove the primary key (_id) while keeping all other fields ?
db.demo471.find({}, {_id: 0});
{ "ClientId": 101, "ClientName": "Chris" }
{ "ClientId": 102, "ClientName": "Bob" }
{ "ClientId": 103, "ClientName": "David" }
Method 2: Exclude Multiple Fields
Remove both _id and ClientId fields ?
db.demo471.find({}, {_id: 0, ClientId: 0});
{ "ClientName": "Chris" }
{ "ClientName": "Bob" }
{ "ClientName": "David" }
Key Points
- Setting
_id: 0in projection excludes the _id field from query results - The _id field remains in the database − only hidden from the output
- You can exclude multiple fields by setting each to 0 in the projection object
Conclusion
Use projection with {_id: 0} to remove the primary key from MongoDB query results. This approach hides the _id field without permanently deleting it from your documents.
Advertisements
