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

岁酱吖の 提交于 2020-03-21 11:15:20

问题


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


回答1:


The cursor.count method is deprecated since pymongo 3.7.

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




回答2:


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/




回答3:


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)



回答4:


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




回答5:


It's actually as simple as

len(list(cursor))

Note that it will however consume the cursor.




回答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.



来源:https://stackoverflow.com/questions/35692719/how-to-get-the-length-of-a-cursor-from-mongodb-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!