汇总多个文档和计数总字段
文档:
{
_id: "___"
finish: false or true
... some field..
}
汇总结果:
{
finish: 10,
non_finish: 3,
results: [
docuemnt,
docuemnt,
...
]
}
有可能吗?我知道如何计数完成
,条件
但是如何汇总文档数组?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案1
$ set
- setfinish_count
和non_finish_count
通过检查finish> finish
字段代码>,如果匹配,则1,else 0。$ group
- 组成null
,总结finish_count
和non_finish_count
fields。将每个文档添加到文档
数组中。$ unset
- 删除documents.finish_count
和documents.non_finish_count
fields。示例mongo playground(解决方案1
null
组组,然后将每个文档添加到文档
array。$ set
- 通过使用finish
($ size )来设置字段>完成:true )和
non_finish
(完成:false
)来自文档
array。示例mongo playground(解决方案2)
Solution 1
$set
- Setfinish_count
andnon_finish_count
fields by checking thefinish
, if match then 1, else 0.$group
- Group bynull
, sum thefinish_count
andnon_finish_count
fields. Add each document intodocuments
array.$unset
- Removedocuments.finish_count
anddocuments.non_finish_count
fields.Sample Mongo Playground (Solution 1)
Solution 2
$group
- Group bynull
, and add each document into thedocuments
array.$set
- Set the fields by counting the size ($size
) of the array by filtering the document withfinish
(finish: true
) andnon_finish
(finish: false
) from thedocuments
array.Sample Mongo Playground (Solution 2)