mongodb 聚合mongo文档,其中一个特定值是一个组,其余值是另一个组

pnwntuvh  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(298)

我有以下结构的数据在我的mongo收集:

  1. {app: 'app1', status: 'success', count: 5},
  2. {app: 'app1', status: 'fail', count: 4},
  3. {app: 'app1', status: 'blocked', count: 3},
  4. {app: 'app1', status: 'transferred', count: 6},
  5. ...

字符串
有更多这样的文档,其中每个应用程序可以有多个状态(不一定是所有的)。我想统计一个组中的所有应用程序的成功状态和第二个组中的所有其他状态,如下所示:

  1. {app: 'app1', status: 'success', count: 5},
  2. {app: 'app1', status: 'failed', count: 13},///4+3+6=13


我该如何编写一个聚合查询呢?我正在尝试,但什么也想不出来,因为这里我必须将“成功”与其他状态分开。
请帮帮我

0lvr5msh

0lvr5msh1#

只需在$group中使用$switch,即可将成功以外的所有情况放入默认分支。

  1. db.collection.aggregate([
  2. {
  3. "$group": {
  4. "_id": {
  5. app: "$app",
  6. status: {
  7. "$switch": {
  8. "branches": [
  9. {
  10. "case": {
  11. $eq: [
  12. "$status",
  13. "success"
  14. ]
  15. },
  16. "then": "success"
  17. }
  18. ],
  19. "default": "failed"
  20. }
  21. }
  22. },
  23. "count": {
  24. "$sum": "$count"
  25. }
  26. }
  27. }
  28. ])

字符串
Mongo Playground

展开查看全部

相关问题