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 only a single document satisfying the criteria in MongoDB?
To find only a single document satisfying specific criteria in MongoDB, use the findOne() method. This method returns the first matching document from the collection, even if multiple documents satisfy the query criteria.
Syntax
db.collection.findOne(query, projection)
Sample Data
db.demo116.insertMany([
{"EmployeeId": 101, "EmployeeName": "John"},
{"EmployeeId": 102, "EmployeeName": "Bob"},
{"EmployeeId": 103, "EmployeeName": "David"},
{"EmployeeId": 102, "EmployeeName": "Mike"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2eff98d8f64a552dae635b"),
ObjectId("5e2eff9fd8f64a552dae635c"),
ObjectId("5e2effa5d8f64a552dae635d"),
ObjectId("5e2effb7d8f64a552dae635e")
]
}
View All Documents
db.demo116.find();
{ "_id" : ObjectId("5e2eff98d8f64a552dae635b"), "EmployeeId" : 101, "EmployeeName" : "John" }
{ "_id" : ObjectId("5e2eff9fd8f64a552dae635c"), "EmployeeId" : 102, "EmployeeName" : "Bob" }
{ "_id" : ObjectId("5e2effa5d8f64a552dae635d"), "EmployeeId" : 103, "EmployeeName" : "David" }
{ "_id" : ObjectId("5e2effb7d8f64a552dae635e"), "EmployeeId" : 102, "EmployeeName" : "Mike" }
Example: Finding Single Document
db.demo116.findOne({"EmployeeId": 102});
{
"_id" : ObjectId("5e2eff9fd8f64a552dae635c"),
"EmployeeId" : 102,
"EmployeeName" : "Bob"
}
Key Points
-
findOne()returns only the first matching document, not all matches. - When multiple documents match (like EmployeeId: 102), only the first one found is returned.
- Returns
nullif no document matches the query criteria.
Conclusion
Use findOne() when you need exactly one document from your query results. It's efficient for retrieving a single record and stops searching after finding the first match.
Advertisements
