How to find a record by _id in MongoDB?


In order to find record by _id in MongoDB, you can use the following syntax

db.yourCollectionName.find({"_id":yourObjectId});

Let us create a collection with documents

> db.findRecordByIdDemo.insertOne({"CustomerName":"Larry","CustomerAge":26});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2c875e2eeda1d5c3671")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Bob","CustomerAge":20});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2d175e2eeda1d5c3672")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"Carol","CustomerAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2d775e2eeda1d5c3673")
}
> db.findRecordByIdDemo.insertOne({"CustomerName":"David","CustomerAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9dc2e375e2eeda1d5c3674")
}

Following is the query to display all documents from a collection with the help of find() method

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

This will produce the following output

{
   "_id" : ObjectId("5c9dc2c875e2eeda1d5c3671"),
   "CustomerName" : "Larry",
   "CustomerAge" : 26
}
{
   "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
   "CustomerName" : "Bob",
   "CustomerAge" : 20
}
{
   "_id" : ObjectId("5c9dc2d775e2eeda1d5c3673"),
   "CustomerName" : "Carol",
   "CustomerAge" : 22
}
{
   "_id" : ObjectId("5c9dc2e375e2eeda1d5c3674"),
   "CustomerName" : "David",
   "CustomerAge" : 24
}
Following is the query to find record by _id in MongoDB:
> db.findRecordByIdDemo.find({"_id":ObjectId("5c9dc2d175e2eeda1d5c3672")}).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9dc2d175e2eeda1d5c3672"),
   "CustomerName" : "Bob",
   "CustomerAge" : 20
}

Updated on: 30-Jul-2019

561 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements