Get amount of objects saved in MongoDB using Pymongo

Question:

I’m trying to get amount of objects saved in MongoDB with

db = myclient.database_sample
my_collection = db["database"]


mydoc = my_collection.find().count()
print("The number of documents in collection : ", mydoc)

but I’m getting an error

mydoc = my_collection.find().count()
AttributeError: 'Cursor' object has no attribute 'count'

I’m using Pymongo 2.0

Asked By: Montana

||

Answers:

The find() function for pymongo returns a cursor object (not an array). Pymongo does include a count_documents function. Meaning the code should look like this:

numberOfDocs = my_collection.count_documents({})

Edit: Updated to correct solution.

Answered By: Patrick

If you wanna keep using .find() methods, you need to convert it to list:

numberOfDocs = len(list(my_collection.find()))
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.