如何将所有文档集合而不是特定字段推送

发布于 2025-01-24 14:04:57 字数 340 浏览 1 评论 0原文

在聚合管道的第一阶段,我使用$ MATD

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

现在我想总结所有A和B 的结果。结果:

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

我尝试$ group$ push ,但是,push只能从对象中推开特定字段,而我需要命名为a和b解析所有这些。

我该怎么做?

I have this array of results in the first stage of the aggregation pipeline, using a $match:

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

Now I want to sum all of the A's and B's and also still have them so I will have something like this as a result:

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

I have tried to $group and $push, however, push only pushes specific fields from the object and I need to name A and B, instead just of parsing all of them.

How can I do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

四叶草在未来唯美盛开 2025-01-31 14:04:57
  1. $ set - 创建新字段总计到sum ab
  2. $ group - 组成的组null,指示总和所有total,并在items array中添加文档。

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

items: {
  $push: "$ROOT"
}

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

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

示例mongo playground

  1. $set - Create new field total to sum a and b.
  2. $group - Group by null, indicate to sum all total and add the document in items array.

With $$ROOT it will add the whole document.

items: {
  $push: "$ROOT"
}

If you want just some fields only, then specify the (desired) document pattern.

items: {
  $push: {
    A: "$a",
    B: "$b"
  }
}
  1. $unset (If use $push $$ROOT) - Remove total field from items field.
db.collection.aggregate([
  {
    $set: {
      total: {
        $sum: [
          "$a",
          "$b"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      total_sum: {
        $sum: "$total"
      },
      items: {
        $push: "$ROOT"
      }
    }
  },
  {
    $unset: "items.total"
  }
])

Sample Mongo Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文