首页 > 解决方案 > mongodb聚合总和项作为嵌套数据

问题描述

这是我在收藏销售中的一些样本数据

[ 
 {group:2, item:a, qty:3 },
 {group:2, item:b, qty:3 },
 {group:2, item:b, qty:2 },
 {group:1, item:a, qty:3 },
 {group:1, item:a, qty:5 },
 {group:1, item:b, qty:5 }
]

我想查询如下数据并将热门组排序到顶部

[
 { group:1, items:[{name:'a',total_qty:8},{name:'b',total_qty:5} ],total_qty:13 },
 { group:2, items:[{name:'a',total_qty:3},{name:'b',total_qty:5} ],total_qty:8 },
]

实际上我们可以在服务器脚本(php,nodejs ...)中循环,但问题是分页。我不能使用跳过来获得正确的结果。

标签: mongodbaggregation-framework

解决方案


您需要将$group聚合与$sum$push累加器一起使用

db.collection.aggregate([
  { "$group": {
    "_id": "$group",
    "items": { "$push": "$$ROOT" },
    "total_qty": { "$sum": "$qty" }
  }},
  { "$sort": { "total_qty": -1 }}
])

推荐阅读