Search code examples
pythonmongodbaggregation-frameworktornado-motor

Mongo aggregate $sum behavior


I have this query in Motor (looks almost exactly as CLI query):

response = yield self.db.orders.aggregate([
        {'$match': {'reader.uid': reader.get('uid'), 'status': {'$in': statuses}}},
        {'$sort': {'create_datetime': -1}},
        {'$project': {'_id': 1, 'status': 1, 'create_datetime': 1, 'documents': 1}},
        {'$group': {
            '_id': 0,
            'info': {'$push': {'status': '$status', 'create_datetime': '$create_datetime', 'documents': '$documents'}},
            'total': {'$sum': 1}
        }},
        {'$skip': skip},
        {'$limit': int(limit)}
    ])

Need to get total count of documents before $skip and $limit. Not sure, how exactly $sum working, but in this query, I get the right result, but when I pass actual _id, the total value is 1:

        {'$group': {
            '_id': '$_id',
            'info': {'$push': {'status': '$status', 'create_datetime': '$create_datetime', 'documents': '$documents'}},
            'total': {'$sum': 1}
        }},

I want to get real _id and right total value in result.

Total newbie in Mongo, all answers are appreciated.


Solution

  • $group groups/aggregate all documents together based on a certain _id.

    When you are grouping documents by _id=0, all documents will be in the same group because all have the same _id that is 0. $sum will count all the documents in the same group by the specified value: 1.

    When you group by the original _id and the _id is unique across your collection you should get sum=1 since there is only one document with that _id => one document in a group.