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 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
_idvalue withObjectId()when querying - The
_idfield is automatically indexed for fast lookups - Use
findOne()for single document retrieval since_idis 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.
Advertisements
