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
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.
Advertisements
