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

后端 未结 6 1452
南笙
南笙 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.

提交回复
热议问题