如何将所有文档集合而不是特定字段推送
在聚合管道的第一阶段,我使用$ 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$ set
- 创建新字段总计
到suma
和b
。$ group
- 组成的组null
,指示总和所有total
,并在items
array中添加文档。使用
$$ root
它将添加整个文档。如果仅想要一些字段,请指定(所需的)文档模式。
$ unset
(如果使用$ push $$ root
) - 删除总计
字段 items 字段。示例mongo playground
$set
- Create new fieldtotal
to suma
andb
.$group
- Group bynull
, indicate to sum alltotal
and add the document initems
array.With
$$ROOT
it will add the whole document.If you want just some fields only, then specify the (desired) document pattern.
$unset
(If use$push $$ROOT
) - Removetotal
field fromitems
field.Sample Mongo Playground