How to find a record by _id in MongoDB?

To find a record by _id in MongoDB, use the find() method with the ObjectId as the query criteria. Every document in MongoDB has a unique _id field that serves as the primary key.

Syntax

db.collectionName.find({"_id": ObjectId("your_object_id")});

Sample Data

Let us create a collection with sample customer documents ?

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

Display All Documents

db.findRecordByIdDemo.find().pretty();
{
    "_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
}

Find Record by _id

To find Bob's record using his specific ObjectId ?

db.findRecordByIdDemo.find({"_id": ObjectId("5c9dc2d175e2eeda1d5c3672")}).pretty();
{
    "_id": ObjectId("5c9dc2d175e2eeda1d5c3672"),
    "CustomerName": "Bob",
    "CustomerAge": 20
}

Key Points

  • Always wrap the _id value with ObjectId() when querying
  • The _id field is automatically indexed for fast lookups
  • Use findOne() for single document retrieval since _id is unique

Conclusion

Finding records by _id in MongoDB is straightforward using find() with the ObjectId() wrapper. This provides the fastest way to retrieve a specific document due to automatic indexing on the _id field.

Updated on: 2026-03-15T00:37:41+05:30

705 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements