【问题标题】:How to $push all of the document in aggregation instead of specific field如何 $push 聚合中的所有文档而不是特定字段
【发布时间】:2022-11-11 01:04:27
【问题描述】:

我在聚合管道的第一阶段有这个结果数组,使用$match:

[
  { a: 1, b: 2 },
  { a: 3, b: 4 }
]

现在我想总结所有的 A 和 B 并且仍然有它们,所以我会得到这样的结果:

{
  total_sum: 10,
  items: [...] // first and second objects ofcourse
}

我尝试过$group 和$push,但是,push 只从对象中推送特定字段,我需要命名 A 和 B,而不是只解析所有字段。

我该怎么做?

【问题讨论】:

  • 这是你试图达到的目标吗? Sample Mongo Playground。只是不明白I need to name A and B, instead just of parse all of them. 是什么意思。
  • 是的,我只是在寻找这个$$ROOT!

标签: mongodb nosql aggregation-framework aggregation


【解决方案1】:
  1. $set - 创建新字段 total 以求和 a 和 b。
  2. $group - 按null 分组,表示对所有total 求和并将文档添加到items 数组中。

    使用$$ROOT 它将添加整个文档。

    items: {
      $push: "$ROOT"
    }
    

    如果您只需要一些字段,请指定(所需的)文档模式。

    items: {
      $push: {
        A: "$a",
        B: "$b"
      }
    }
    
    1. $unset(如果使用 $push $$ROOT) - 从 items 字段中删除 total 字段。
    db.collection.aggregate([
      {
        $set: {
          total: {
            $sum: [
              "$a",
              "$b"
            ]
          }
        }
      },
      {
        $group: {
          _id: null,
          total_sum: {
            $sum: "$total"
          },
          items: {
            $push: "$$ROOT"
          }
        }
      },
      {
        $unset: "items.total"
      }
    ])
    

    Sample Mongo Playground

【讨论】:

    猜你喜欢
    • 2020-09-03
    • 2021-06-19
    • 2020-10-02
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多