How to remove primary key from MongoDB?


To remove primary key in MongoDB, set _id value to 0 i.e. set the field you want to exclude as 0 in find(). Let us create a collection with documents −

> db.demo471.insertOne({"ClientId":101,"ClientName":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e805711b0f3fa88e2279077")
}
> db.demo471.insertOne({"ClientId":102,"ClientName":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e80571db0f3fa88e2279078")
}
> db.demo471.insertOne({"ClientId":103,"ClientName":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e805724b0f3fa88e2279079")
}

Display all documents from a collection with the help of find() method −

> db.demo471.find();

This will produce the following output −

{ "_id" : ObjectId("5e805711b0f3fa88e2279077"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e80571db0f3fa88e2279078"), "ClientId" : 102, "ClientName" : "Bob" }
{ "_id" : ObjectId("5e805724b0f3fa88e2279079"), "ClientId" : 103, "ClientName" : "David" }

Following is the query to remove primary key in MongoDB −

> db.demo471.find({},{_id:0,ClientId:0});;

This will produce the following output −

{ "ClientName" : "Chris" }
{ "ClientName" : "Bob" }
{ "ClientName" : "David" }

Updated on: 11-May-2020

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements