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
Can I get the first item in a Cursor object in MongoDB?
Yes, you can get the first item in a cursor object in MongoDB using the findOne() method or by applying the limit(1) method to a cursor.
Syntax
// Method 1: Using findOne()
db.collection.findOne();
db.collection.findOne({condition});
// Method 2: Using find().limit(1)
db.collection.find().limit(1);
Sample Data
db.getFirstItemDemo.insertMany([
{"CustomerName": "Chris", "CustomerAge": 28},
{"CustomerName": "Larry", "CustomerAge": 26},
{"CustomerName": "Robert", "CustomerAge": 29},
{"CustomerName": "David", "CustomerAge": 39}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c989059330fd0aa0d2fe4c1"),
ObjectId("5c989063330fd0aa0d2fe4c2"),
ObjectId("5c98906d330fd0aa0d2fe4c3"),
ObjectId("5c989081330fd0aa0d2fe4c4")
]
}
Display all documents from the collection ?
db.getFirstItemDemo.find().pretty();
{
"_id": ObjectId("5c989059330fd0aa0d2fe4c1"),
"CustomerName": "Chris",
"CustomerAge": 28
}
{
"_id": ObjectId("5c989063330fd0aa0d2fe4c2"),
"CustomerName": "Larry",
"CustomerAge": 26
}
{
"_id": ObjectId("5c98906d330fd0aa0d2fe4c3"),
"CustomerName": "Robert",
"CustomerAge": 29
}
{
"_id": ObjectId("5c989081330fd0aa0d2fe4c4"),
"CustomerName": "David",
"CustomerAge": 39
}
Method 1: Using findOne()
Get the first document from the collection ?
db.getFirstItemDemo.findOne();
{
"_id": ObjectId("5c989059330fd0aa0d2fe4c1"),
"CustomerName": "Chris",
"CustomerAge": 28
}
Get a specific document using a condition ?
db.getFirstItemDemo.findOne({"CustomerAge": 39});
{
"_id": ObjectId("5c989081330fd0aa0d2fe4c4"),
"CustomerName": "David",
"CustomerAge": 39
}
Method 2: Using find().limit(1)
Alternative approach to get the first document ?
db.getFirstItemDemo.find().limit(1);
Key Differences
- findOne() returns a single document object directly
- find().limit(1) returns a cursor containing one document
- findOne() is more efficient for retrieving a single document
Conclusion
Use findOne() to directly retrieve the first document from a cursor. It's the most efficient method for getting a single document and returns the document object directly rather than a cursor.
Advertisements
