What is a PyMongo Cursor? (original) (raw)
Last Updated : 25 Jul, 2025
When working with **MongoDB in Python using **PyMongo, you typically retrieve data from a collection using the find() method. But instead of getting all the matching documents at once, PyMongo returns something called a cursor.
A PyMongo cursor is a special iterable object that acts like a pointer to the result set of a MongoDB query. It allows you to fetch and process query results one document at a time rather than loading everything into memory at once.
Why do we need Cursor
Using a cursor provides several important advantages, especially when dealing with large datasets:
- **Memory-efficient: Documents are retrieved in small batches instead of all at once, preventing memory overload.
- **Lazy loading: Results are fetched as you iterate, which avoids blocking your application.
- **Incremental processing: You can handle one document at a time in a loop, which is great for streaming, filtering or transforming data.
- **Improved performance: Reduces pressure on both the client and the MongoDB server.
Cursor Customization Options
You can fine-tune the data returned by the cursor using:
- **projection : to select specific fields from documents
- **sort() : to order results based on one or more fields
- **limit() : to restrict the number of documents returned
- **skip() : to skip a specified number of documents
Sample database is as follows: 
**Example: Using Cursor in PyMongo
javascript `
from pymongo import MongoClient
Connecting to mongodb
client = MongoClient('mongodb://localhost:27017/')
with client:
db = client.GFG
lectures = db.lecture.find()
print(lectures.next())
print(lectures.next())
print(lectures.next())
print("\nRemaining Lectures\n")
print(list(lectures))`
**Output:

**Explanation:
- **find() method returns the cursor object.
- **next() method we get the next document in the collection.
- **list() method, we can transform the cursor to a Python list.