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

后端 未结 6 1479
南笙
南笙 2021-02-19 01:49

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

相关标签:
6条回答
  • 2021-02-19 02:15

    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.

    0 讨论(0)
  • 2021-02-19 02:17

    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/

    0 讨论(0)
  • 2021-02-19 02:17

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

    0 讨论(0)
  • 2021-02-19 02:30

    The cursor.count method is deprecated since pymongo 3.7.

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

    0 讨论(0)
  • 2021-02-19 02:35

    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)
    
    0 讨论(0)
  • 2021-02-19 02:36

    It's actually as simple as

    len(list(cursor))
    

    Note that it will however consume the cursor.

    0 讨论(0)
提交回复
热议问题