How to search document in MongoDB by _id

To search a document in MongoDB by _id, you need to use the ObjectId() function to wrap the _id value, since MongoDB stores document IDs as ObjectId objects.

Syntax

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

Create Sample Data

Let us create a collection with sample documents ?

db.searchDocumentDemo.insertMany([
    {"UserId": 1, "UserName": "Larry"},
    {"UserId": 2, "UserName": "Mike"},
    {"UserId": 3, "UserName": "David"},
    {"UserId": 4, "UserName": "Chris"},
    {"UserId": 5, "UserName": "Robert"},
    {"UserId": 6, "UserName": "Sam"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c97a8e4330fd0aa0d2fe487"),
        ObjectId("5c97a8ea330fd0aa0d2fe488"),
        ObjectId("5c97a8f1330fd0aa0d2fe489"),
        ObjectId("5c97a8fa330fd0aa0d2fe48a"),
        ObjectId("5c97a901330fd0aa0d2fe48b"),
        ObjectId("5c97a911330fd0aa0d2fe48c")
    ]
}

Display All Documents

db.searchDocumentDemo.find().pretty();
{
    "_id": ObjectId("5c97a8e4330fd0aa0d2fe487"),
    "UserId": 1,
    "UserName": "Larry"
}
{
    "_id": ObjectId("5c97a8ea330fd0aa0d2fe488"),
    "UserId": 2,
    "UserName": "Mike"
}
{
    "_id": ObjectId("5c97a8f1330fd0aa0d2fe489"),
    "UserId": 3,
    "UserName": "David"
}
{
    "_id": ObjectId("5c97a8fa330fd0aa0d2fe48a"),
    "UserId": 4,
    "UserName": "Chris"
}
{
    "_id": ObjectId("5c97a901330fd0aa0d2fe48b"),
    "UserId": 5,
    "UserName": "Robert"
}
{
    "_id": ObjectId("5c97a911330fd0aa0d2fe48c"),
    "UserId": 6,
    "UserName": "Sam"
}

Example: Search by _id

Now, let us search for a specific document by its _id ?

db.searchDocumentDemo.find({"_id": ObjectId("5c97a901330fd0aa0d2fe48b")}).pretty();
{
    "_id": ObjectId("5c97a901330fd0aa0d2fe48b"),
    "UserId": 5,
    "UserName": "Robert"
}

Key Points

  • Always wrap the _id value with ObjectId() when searching
  • Without ObjectId(), MongoDB treats the value as a plain string
  • The _id field is automatically indexed, making searches extremely fast

Conclusion

Searching documents by _id in MongoDB requires the ObjectId() function to properly match the ObjectId data type. This method provides the fastest document retrieval since _id is automatically indexed.

Updated on: 2026-03-15T00:23:53+05:30

475 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements