【问题标题】:Mongo aggregate group by pairMongo 逐对聚合
【发布时间】:2021-12-21 05:36:19
【问题描述】:

我有这样的收藏

User Receiver IsRead
A B false
B A false
A B false
A C false
C A false

如何按用户和接收者分组以获得这样的结果

Combined Field Messages
AB OR BA 3
AC OR CA 2

试过了

$group: {
    _id: {$or: [{userId: "$recipientId", recipientId: "$userId"}, {userId: "$userId", recipientId: "$recipientId"}]},
    messages: {$sum: {$cond: [{$eq: ['$isRead', false]}, 1, 0]}} // count
}

【问题讨论】:

    标签: mongodb group-by aggregation


    【解决方案1】:

    您可以将$group 键设置为UserReceiver 字段的$setUnion

    db.collection.aggregate([
      {
        $group: {
          _id: {
            "$setUnion": [
              [
                "$User"
              ],
              [
                "$Receiver"
              ]
            ]
          },
          "Messages": {
            $sum: {
              "$cond": {
                "if": {
                  $not: "$IsRead"
                },
                "then": 1,
                "else": 0
              }
            }
          }
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 2018-07-15
      • 2017-08-24
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多