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
Find a document with ObjectID in MongoDB?
To find a document with ObjectId in MongoDB, use the ObjectId() constructor in your query to match the specific _id field value.
Syntax
db.collectionName.find({"_id": ObjectId("yourObjectIdValue")}).pretty();
Sample Data
Let us create a collection with sample documents to demonstrate finding by ObjectId ?
db.findDocumentWithObjectIdDemo.insertMany([
{"UserName": "Larry"},
{"UserName": "Mike", "UserAge": 23},
{"UserName": "Carol", "UserAge": 26, "UserHobby": ["Learning", "Photography"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c90e4384afe5c1d2279d69b"),
ObjectId("5c90e4444afe5c1d2279d69c"),
ObjectId("5c90e4704afe5c1d2279d69d")
]
}
Display all documents to see the generated ObjectIds ?
db.findDocumentWithObjectIdDemo.find().pretty();
{ "_id": ObjectId("5c90e4384afe5c1d2279d69b"), "UserName": "Larry" }
{
"_id": ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName": "Mike",
"UserAge": 23
}
{
"_id": ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName": "Carol",
"UserAge": 26,
"UserHobby": [
"Learning",
"Photography"
]
}
Example 1: Find Carol's Document
db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();
{
"_id": ObjectId("5c90e4704afe5c1d2279d69d"),
"UserName": "Carol",
"UserAge": 26,
"UserHobby": [
"Learning",
"Photography"
]
}
Example 2: Find Mike's Document
db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();
{
"_id": ObjectId("5c90e4444afe5c1d2279d69c"),
"UserName": "Mike",
"UserAge": 23
}
Key Points
- Always wrap the ObjectId string with
ObjectId()constructor in queries - ObjectId queries return at most one document since
_idis unique - Use
.pretty()for formatted output display
Conclusion
Finding documents by ObjectId requires using the ObjectId() constructor with the string value. This is the most efficient way to retrieve a specific document since _id is automatically indexed.
Advertisements
