简体   繁体   中英

count on aggregate in mongodb

this my query for aggregate in pymongo:

db.connection_log.aggregate([
    { '$match': {
        'login_time': {'$gte': datetime.datetime(2014, 5, 30, 6, 57)}
    }},
    { '$group': {
        '_id': {
            'username': '$username',
            'ras_id': '$ras_id',
            'user_id': '$user_id'
        }, 
        'total': { '$sum': '$type_details.in_bytes'}, 
        'total1': {'$sum': '$type_details.out_bytes'}
    }}, 
    { '$sort': {'total': 1, 'total1': 1}}
])

How to count all result in aggregate?

Add to the end of your aggregation pipeline:

$group: {
    _id:null,
    count:{
        $sum:1
    }
}

SQL to Aggregation Mapping Chart

Well if you really want your results with a total count combined then you can always just push the results into their own array:

result = db.connection_log.aggregate([
    { '$match': {
        'login_time': {'$gte': datetime.datetime(2014, 5, 30, 6, 57)}
    }},
    { '$group': {
        '_id': {
            'username': '$username',
            'ras_id': '$ras_id',
            'user_id': '$user_id'
        }, 
        'total': { '$sum': '$type_details.in_bytes'}, 
        'total1': {'$sum': '$type_details.out_bytes'}
    }}, 
    { '$sort': {'total': 1, 'total1': 1}},
    { '$group' {
        '_id': null,
        'results': { 
            '$push': {
               '_id': '$_id',
               'total': '$total',
               'total1': '$total1'
            }
        },
        'count': { '$sum': 1 }
    }}
])

And if you are using MongoDB 2.6 or greater you can just '$push': '$$ROOT' instead of actually specifying all of the document fields there.

But really, unless you are using MongoDB 2.6 and are explicitly asking for a cursor as a result, then that result is actually returned as an array already without adding an inner array for results with a count. So just get the length of the array, which in python is:

len(result)

If you are indeed using a cursor for a large result-set or otherwise using $limit and $skip to "page" results then you will need to do two queries with one just summarizing the "total count", but otherwise you just don't need to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM