Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
