'How to get the length of a cursor from mongodb using python?

I'm looking for a feasible way to get the length of cursor got from MongoDB.



Solution 1:[1]

It's actually as simple as

len(list(cursor))

Note that it will however consume the cursor.

Solution 2:[2]

The cursor.count method is deprecated since pymongo 3.7.

The recommended method is to use the count_documents method of the collection.

Solution 3:[3]

cursor.count()

Counts the number of documents referenced by a cursor. Append the count() method to a find() query to return the number of matching documents. The operation does not perform the query but instead counts the results that would be returned by the query.

db.collection.find(<query>).count()

https://docs.mongodb.com/manual/reference/method/db.collection.count/

Solution 4:[4]

The variant of the previous answer:

len(list(cursor.clone()))

doesn't consume cursor

Solution 5:[5]

According to the pymongo documentation, a Pymongo cursor, has a count method:

count(with_limit_and_skip=False)

By default this method returns the total length of the cursor, for example:

cursor.count()

If you call this method with with_limit_and_skip=True, the returned value takes limit and skip queries into account. For example, the following query will return 5 (assuming you have more than 5 documents):

cursor.limit(5).count(True)

Solution 6:[6]

For some reason, some aggregations return an object that doesn't have the same methods, maybe different class, simple solution, convert the pseudo cursor to an array:

// A simple aggregation with `group`
var cursor = db.getCollection('collection').aggregate([
    {$match: {
        "property": {"$exists": true }
    }},
    {$group: { 
        _id: '$groupable',
        count: {$sum: 1}
    }},
    {$sort: {
        count: -1
    }}
]);

// Converting the "cursor" into an array
var cursor_array = cursor.toArray();

// Looping as an array using `for` instead of `while`
for (var i = 0; i < cursor_array.length; i++) {
    print(cursor_array[i]._id+'\t'+cursor_array[i].count);
}

Notice this solution is only for the shell, I don't know if this array method exists in other libraries.

Solution 7:[7]

I find that using cursor.iter().count() is a feasible way to resolve this problem

Solution 8:[8]

I was able to do count it this way:

def count():
    collection = db[col_name]
    count = collection.count_documents({"visited" : True})
    
    return count

Solution 9:[9]

len(list(cursor.clone())) worked really well for me, does not consume the editor so it can be use straight with your variable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gabriel Fair
Solution 3
Solution 4 Yaroslav Boichuk
Solution 5
Solution 6 Rodrigo Polo
Solution 7 jtlz2
Solution 8 Juan Zamora
Solution 9 Kaio Santos