Removing _id element from PyMongo results?


To remove the _id element, you can use the following syntax −

db.yourCollectionName.find({},{'_id': false}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.removingidElementDemo.insertOne({"UserName":"John",
... "UserAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9153fd4afe5c1d2279d6ad")
}
> db.removingidElementDemo.insertOne({"UserName":"Carol", "UserAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9154084afe5c1d2279d6ae")
}
> db.removingidElementDemo.insertOne({"UserName":"David", "UserAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9154154afe5c1d2279d6af")
}
> db.removingidElementDemo.insertOne({"UserName":"Mike", "UserAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9154204afe5c1d2279d6b0")
}
> db.removingidElementDemo.insertOne({"UserName":"Chris", "UserAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c91542c4afe5c1d2279d6b1")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.removingidElementDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c9153fd4afe5c1d2279d6ad"),
   "UserName" : "John",
   "UserAge" : 21
}
{
   "_id" : ObjectId("5c9154084afe5c1d2279d6ae"),
   "UserName" : "Carol",
   "UserAge" : 24
}
{
   "_id" : ObjectId("5c9154154afe5c1d2279d6af"),
   "UserName" : "David",
   "UserAge" : 22
}
{
   "_id" : ObjectId("5c9154204afe5c1d2279d6b0"),
   "UserName" : "Mike",
   "UserAge" : 26
}
{
   "_id" : ObjectId("5c91542c4afe5c1d2279d6b1"),
   "UserName" : "Chris",
   "UserAge" : 20
}

Here is the query to remove an _id element from PyMongo −

> db.removingidElementDemo.find({},{'_id': false}).pretty();

The following is the output in which you cannot see the _id element since we have removed it −

{ "UserName" : "John", "UserAge" : 21 }
{ "UserName" : "Carol", "UserAge" : 24 }
{ "UserName" : "David", "UserAge" : 22 }
{ "UserName" : "Mike", "UserAge" : 26 }
{ "UserName" : "Chris", "UserAge" : 20 }

Updated on: 30-Jul-2019

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements