按几个字段分组并使用两个条件自定义总和

时间:2019-08-18 12:13:43

标签: mongodb mongodb-query aggregation-framework

我想用两个条件对行进行分组。第一个获得total(现在可以正常工作),第二个获得unread消息。我无法想象该怎么做。插入内容为:

db.messages.insert({'source_user': 'test1', 'destination_user': 'test2', 'is_read': true})
db.messages.insert({'source_user': 'test1', 'destination_user': 'test2', 'is_read': false})
db.messages.insert({'source_user': 'test1', 'destination_user': 'test3', 'is_read': true})

我的代码:

db.messages.aggregate([
    {'$match': {'source_user': user}},
    {'$group': {
        '_id': {
            'source_user': '$source_user',
            'destination_user': '$destination_user',
            'is_read': '$is_read'
        },
        'total': {'$sum': 1}}
    },
    {'$project': {
        'source_user': '$_id.source_user',
        'destination_user': '$_id.destination_user',
        #'unread': {'$sum': {'$_id.is_read': False}},
        'total': '$total',
        '_id': 0
    }}
    ])

因此我想得到:

[{
    'source_user': 'test1',
    'destination_user': 'test2',
    'unread': 1,
    'total': 2
  }, {
    'source_user': 'test1',
    'destination_user': 'test3',
    'unread': 0,
    'total': 1
 }
]

我应该添加一个新组,还是可以在同一组中使用$is_read标志?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用与总数相同的方式来计数未读邮件,但是您仅需要为已读<的邮件应用$cond来添加0 / strong>,另外1

db.messages.aggregate([
    {'$match': {'source_user': user}},
    {'$group': {
        '_id': {
            'source_user': '$source_user',
            'destination_user': '$destination_user'
        },
        'total': {'$sum': 1},
        'unread': {'$sum': { '$cond': [ '$is_read', 0, 1 ] }}
        }
    },
    {'$project': {
        'source_user': '$_id.source_user',
        'destination_user': '$_id.destination_user',
        'total': 1,
        'unread': 1,
        '_id': 0
    }}
])

MongoDB Playground