We will have to know how to use a cursor in Pymongo when querying documents on a database in MongoDB at Python. A cursor in Pymongo is nothing more than a list that houses the documents resulting from the query.
In this example we are going to perform a query on a database MongoDB using Pymongo to be able to manage, traverse and print the results of the cursor.
The first thing will be to import the MongoClient object, which is what will allow us to connect with MongoDB from Python.
from pymongo import MongoClient
With the MongoClient object we are going to connect to the server, choose a database (users) and a collection (list).
client = MongoClient()
db = client.users
listing = db.listing
Now we are going to execute the query using the .find() method
users = listing.find()
Which would be the same as having written:
users = db.list.find()
Much closer to MongoDB syntax.
At the end in the users variable we have the cursor with all the documents resulting from the query. We are going to use a for in structure to go through the documents and upload them to the screen.
for user in users:
print user
On the screen we will obtain all the JSON documents that the query has returned to us.
In this simple way we have created a cursor in Pymongo with the result of a query to MongoDB.
