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
What is return type of db.collection.find() in MongoDB?
The db.collection.find() method in MongoDB returns a cursor object, not the actual documents. A cursor is an iterable object that points to the result set of a query and allows you to traverse through the documents.
Syntax
db.collection.find(query, projection)
The cursor returned can be used to iterate over results or apply additional methods like limit(), sort(), etc.
Sample Data
Let us first create a collection with documents ?
db.findCursorDemo.insertMany([
{"ClientFirstName": "John", "ClientLastName": "Smith"},
{"ClientFirstName": "Carol", "ClientLastName": "Taylor"},
{"ClientFirstName": "David", "ClientLastName": "Miller"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd00a1c588d4a6447b2e05c"),
ObjectId("5cd00a26588d4a6447b2e05d"),
ObjectId("5cd00a33588d4a6447b2e05e")
]
}
Example: Using the find() Cursor
The following query demonstrates how find() returns a cursor ?
db.findCursorDemo.find();
{ "_id": ObjectId("5cd00a1c588d4a6447b2e05c"), "ClientFirstName": "John", "ClientLastName": "Smith" }
{ "_id": ObjectId("5cd00a26588d4a6447b2e05d"), "ClientFirstName": "Carol", "ClientLastName": "Taylor" }
{ "_id": ObjectId("5cd00a33588d4a6447b2e05e"), "ClientFirstName": "David", "ClientLastName": "Miller" }
Key Points
- The
find()method returns a cursor object, not raw documents. - MongoDB shell automatically iterates the cursor to display up to 20 documents.
- You can chain cursor methods like
limit(),sort(), andskip()to the result. - Use
toArray()to convert the cursor to an array of documents.
Conclusion
The db.collection.find() method returns a cursor object that provides flexible iteration over query results. This design allows for efficient memory usage and the ability to apply additional operations before retrieving documents.
Advertisements
