Use ObjectId under findOne() to fetch a specific record in MongoDB?

To fetch a specific record in MongoDB using ObjectId with the findOne() method, pass the ObjectId as the query criteria. The findOne() method returns the first document that matches the specified ObjectId.

Syntax

db.collection.findOne({"_id": ObjectId("objectid_value")});

Create Sample Data

db.findOneWorkingDemo.insertMany([
    {"ClientId": 1, "ClientName": "Larry", "ClientAge": 26},
    {"ClientId": 2, "ClientName": "Chris", "ClientAge": 28},
    {"ClientId": 3, "ClientName": "Robert", "ClientAge": 34}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd7c1716d78f205348bc64d"),
        ObjectId("5cd7c17d6d78f205348bc64e"),
        ObjectId("5cd7c1896d78f205348bc64f")
    ]
}

Display All Documents

db.findOneWorkingDemo.find().pretty();
{
    "_id": ObjectId("5cd7c1716d78f205348bc64d"),
    "ClientId": 1,
    "ClientName": "Larry",
    "ClientAge": 26
}
{
    "_id": ObjectId("5cd7c17d6d78f205348bc64e"),
    "ClientId": 2,
    "ClientName": "Chris",
    "ClientAge": 28
}
{
    "_id": ObjectId("5cd7c1896d78f205348bc64f"),
    "ClientId": 3,
    "ClientName": "Robert",
    "ClientAge": 34
}

Example: Find Document by ObjectId

Fetch the document with ObjectId "5cd7c17d6d78f205348bc64e" ?

db.findOneWorkingDemo.findOne({"_id": ObjectId("5cd7c17d6d78f205348bc64e")});
{
    "_id": ObjectId("5cd7c17d6d78f205348bc64e"),
    "ClientId": 2,
    "ClientName": "Chris",
    "ClientAge": 28
}

Conclusion

Using findOne() with ObjectId provides an efficient way to retrieve a specific document by its unique identifier. The method returns exactly one document that matches the given ObjectId criteria.

Updated on: 2026-03-15T01:19:26+05:30

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements