【问题标题】:MongoDB aggregation '$sortBy' using combination of fields使用字段组合的 MongoDB 聚合“$sortBy”
【发布时间】:2022-03-10 13:21:32
【问题描述】:

我有一个包含字段 senderreceiver 的集合,我想通过聚合来执行一个组包含字段 senderreceiver 的集合。

例子

收藏:

[
  { "id": 1, "sender": "A", "receiver": "B"},
  { "id": 3, "sender": "B", "receiver": "A"},
  { "id": 4, "sender": "B", "receiver": "C"},
  { "id": 5, "sender": "C", "receiver": "A"}
]

预期的汇总输出将是:

[
  { "_id": { "user1": "A", "user2": "B"}, "total": 2 },
  { "_id": { "user1": "A", "user2": "C"}, "total": 1 },
  { "_id": { "user1": "B", "user2": "C"}, "total": 1 },
]

这可以通过使用 MongoDB 聚合实现吗?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:
    1. $addFields:添加带有senderreceiver 数组的users 字段。
    2. $unwind:解构数组字段users,用于第3步中的排序。
    3. $sort:按字母顺序对步骤 2 中解构的 users 数组进行排序。
    4. $group:按id 分组,将users 构造到数组中。
    5. $group:按user1user2$count 分组。
    6. $sort:按字母顺序对_id.user1_id.user2 进行排序。
    db.collection.aggregate([
      {
        $addFields: {
          "users": [
            "$sender",
            "$receiver"
          ]
        }
      },
      {
        $unwind: "$users"
      },
      {
        $sort: {
          "users": 1
        }
      },
      {
        $group: {
          "_id": "$id",
          "users": {
            $push: "$users"
          }
        }
      },
      {
        $group: {
          "_id": {
            "user1": {
              $arrayElemAt: [
                "$users",
                0
              ]
            },
            "user2": {
              $arrayElemAt: [
                "$users",
                1
              ]
            }
          },
          "total": {
            $count: {}
          }
        }
      },
      {
        $sort: {
          "_id.user1": 1,
          "_id.user2": 1
        }
      }
    ])
    

    输出

    [
      {
        "_id": {
          "user1": "A",
          "user2": "B"
        },
        "total": 2
      },
      {
        "_id": {
          "user1": "A",
          "user2": "C"
        },
        "total": 1
      },
      {
        "_id": {
          "user1": "B",
          "user2": "C"
        },
        "total": 1
      }
    ]
    

    Sample Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2016-08-16
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多