QIAN KEQIAO
QIAN KEQIAO

Reputation: 641

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.

Upvotes: 53

Views: 75433

Answers (11)

efeakaroz13
efeakaroz13

Reputation: 143

Hello I was trying to find a solution to this and I figured it out.

#Count documents takes a filter object inside(a dict) and you need to call it
#after a Collection object not cursor.
portfolio.count_documents({})

I hope this helps

Upvotes: 0

sjamr10
sjamr10

Reputation: 13

How about sum(1 for _ in cursor.clone()) so that you get the count but using constant memory instead of creating a new list. And you don't have to make another query to mongo with this solution.

Upvotes: 0

Kaio Santos
Kaio Santos

Reputation: 81

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

Upvotes: 7

QIAN KEQIAO
QIAN KEQIAO

Reputation: 641

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

Upvotes: 3

Juan Zamora
Juan Zamora

Reputation: 11

I was able to do count it this way:

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

Upvotes: 1

Sa Lzrnk
Sa Lzrnk

Reputation: 381

The variant of the previous answer:

len(list(cursor.clone()))

doesn't consume cursor

Upvotes: 25

Jérôme
Jérôme

Reputation: 14704

The cursor.count method is deprecated since pymongo 3.7.

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

Upvotes: 26

Rodrigo Polo
Rodrigo Polo

Reputation: 4784

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.

Upvotes: 1

Skippy le Grand Gourou
Skippy le Grand Gourou

Reputation: 7724

It's actually as simple as

len(list(cursor))

Note that it will however consume the cursor.

Upvotes: 48

Kamlesh
Kamlesh

Reputation: 2056

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/

Upvotes: 8

Alex
Alex

Reputation: 21766

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)

Upvotes: 3

Related Questions