Skip to content
Related Articles

Related Articles

Improve Article
What is a PyMongo Cursor?
  • Last Updated : 22 Jun, 2020

MongoDB is an open-source database management system that uses the NoSql database to store large amounts of data. MongoDB uses collection and documents instead of tables like traditional relational databases. MongoDB documents are similar to JSON objects but use a variant called Binary JSON (BSON) that accommodates more data types.

What is a Cursor?

When you use the function db.collection.find() to search documents in collections than as a result it returns a pointer. That pointer is known as a cursor. Consider if we have 2 documents in our collection, then cursor object will point to the first document and then iterate through all documents which are present in our collection.

PyMongo Cursor

As we already discussed what is a cursor. It is basically a tool for iterating over MongoDB queries. This cursor instance is returned by the find() method. Consider the below example for better understanding.

Example:



Sample Database:

python-mongodb-sample-database6




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:

python-mongodb-cursor

In this, find() method returns the cursor object.

lectures = db.lecture.find()

With the next() method we get the next document in the collection.

lectures.next()

With the list() method, we can transform the cursor to a Python list.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :