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
Difference between find() and findOne() methods in MongoDB?
The findOne() method returns the first document if a query matches, otherwise returns null. The find() method never returns null ? it always returns a cursor object, even when no documents match.
Syntax
// findOne() - returns single document or null db.collection.findOne(query, projection); // find() - returns cursor object db.collection.find(query, projection);
Sample Data
Let us create an empty collection to demonstrate the behavior ?
db.createCollection('emptyCollection');
{ "ok" : 1 }
Check the document count in the collection ?
db.emptyCollection.count();
0
Example 1: findOne() on Empty Collection
Test findOne() behavior when no documents exist ?
if(db.emptyCollection.findOne()){
print("Returns Document");
} else {
print("Returns null");
}
Returns null
Example 2: find() on Empty Collection
Test find() behavior when no documents exist ?
if(db.emptyCollection.find()){
print("Returns Cursor");
} else {
print("Returns null");
}
Returns Cursor
Key Differences
| Aspect | find() | findOne() |
|---|---|---|
| Return Type | Cursor object (always) | Document or null |
| Empty Collection | Returns empty cursor | Returns null |
| Multiple Matches | Returns all matching documents | Returns first match only |
| Iteration | Requires iteration through cursor | Direct document access |
Conclusion
Use findOne() when you need a single document and want null-checking capability. Use find() when you need multiple documents or want consistent cursor-based processing regardless of result count.
Advertisements
