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
Retrieving the first document in a MongoDB collection?
To retrieve the first document in a MongoDB collection, use the findOne() method. This returns the first document from the collection in natural insertion order.
Syntax
db.collectionName.findOne(); // Store in variable and display var result = db.collectionName.findOne(); result;
Sample Data
db.retrieveFirstDocumentDemo.insertMany([
{"ClientName": "Robert", "ClientAge": 23},
{"ClientName": "Chris", "ClientAge": 26},
{"ClientName": "Larry", "ClientAge": 29},
{"ClientName": "David", "ClientAge": 39}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca2325966324ffac2a7dc6d"),
ObjectId("5ca2326266324ffac2a7dc6e"),
ObjectId("5ca2326a66324ffac2a7dc6f"),
ObjectId("5ca2327566324ffac2a7dc70")
]
}
Display All Documents
db.retrieveFirstDocumentDemo.find().pretty();
{
"_id": ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName": "Robert",
"ClientAge": 23
}
{
"_id": ObjectId("5ca2326266324ffac2a7dc6e"),
"ClientName": "Chris",
"ClientAge": 26
}
{
"_id": ObjectId("5ca2326a66324ffac2a7dc6f"),
"ClientName": "Larry",
"ClientAge": 29
}
{
"_id": ObjectId("5ca2327566324ffac2a7dc70"),
"ClientName": "David",
"ClientAge": 39
}
Retrieve First Document
var firstDocumentOnly = db.retrieveFirstDocumentDemo.findOne(); firstDocumentOnly;
{
"_id": ObjectId("5ca2325966324ffac2a7dc6d"),
"ClientName": "Robert",
"ClientAge": 23
}
Key Points
-
findOne()returns the first document in natural insertion order. - Returns
nullif no documents exist in the collection. - More efficient than
find().limit(1)for retrieving a single document.
Conclusion
The findOne() method efficiently retrieves the first document from a MongoDB collection. It returns the document in natural order or null if the collection is empty.
Advertisements
