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
Get the top most document from a MongoDB collection
To get the topmost document from a MongoDB collection, use the find() method along with limit(1). This retrieves the first document based on the natural insertion order or specified sorting criteria.
Syntax
db.collection.find().limit(1);
Sample Data
db.demo681.insertMany([
{_id: 101, Name: "Chris"},
{_id: 102, Name: "Bob"},
{_id: 103, Name: "David"},
{_id: 104, Name: "Bob"},
{_id: 105, Name: "Sam"}
]);
{
"acknowledged": true,
"insertedIds": [101, 102, 103, 104, 105]
}
Display all documents from the collection ?
db.demo681.find();
{ "_id": 101, "Name": "Chris" }
{ "_id": 102, "Name": "Bob" }
{ "_id": 103, "Name": "David" }
{ "_id": 104, "Name": "Bob" }
{ "_id": 105, "Name": "Sam" }
Example: Get Top Document
Retrieve the topmost document from the collection ?
db.demo681.find().limit(1);
{ "_id": 101, "Name": "Chris" }
Key Points
-
limit(1)restricts the result to only the first document. - Without sorting, it returns the first document in natural order (insertion order).
- Use
sort()beforelimit(1)to get the top document based on specific criteria.
Conclusion
The find().limit(1) method efficiently retrieves the topmost document from a MongoDB collection. Combine with sort() for retrieving the top document based on custom ordering criteria.
Advertisements
