Search code examples
pythonmongodbpymongo

Determine the number of pymongo documents


When specifying the number of documents in pymongo , does it retrieve all the documents and then limit them using Python code, or does it fetch only 10 documents directly from the server?

For example, is this :

data=mydb[collection].find().limit(10)

like this ?:

data=mydb[collection].find()
data=data.limit(10)

If so, what is the way to limit the number of records so that only 10 documents come from the server .


Solution

  • It fetches only 10. Remember that PyMongo returns a cursor. Data is only retrieved after starting the iteration on the cursor.

    If you wonder, it simply adds a $limit aggregation to the pipeline that is requested from the server.