【问题标题】:Use $group with find in mongodb node.js在 mongodb node.js 中使用 $group 和 find
【发布时间】:2017-02-11 02:25:25
【问题描述】:

我想从order 集合中按user_id 分组,其中有很多条目,但我想获取下达更多订单的前 5 名用户,并对特定用户的总价格求和。

例如,如果我下了 10 个订单,我想获取我的 ID 和所有订单的总和。 我使用了下面的代码,但它不起作用:

Order.find({$group : { user_id : "$user_id"}},function(error,fetchAllTopUsers){
    console.log('##################');
      console.log(fetchAllTopUsers);
    })

我已经检查了这个例子,但他们没有使用 $group 的 find。我是 Node.js 和 MongoDB 的新手。

Query and sum all with mongoose

示例文档

{ user_id : '57c7f4312b3c9771219bd21c', totalprice : 100 },
{ user_id : '57c7f4312b3c9771219bd21c', totalprice : 59 },
{ user_id : '57c7f4312b3c9771219bd21c', totalprice : 26 },
{ user_id : '57c7f4312b3c9771219bd21c', totalprice : 533 },
{ user_id : '57c7f4312b3c9771219bd21c', totalprice : 544 },    
{ user_id : '57efb93fdc78c816a3a15c4a', totalprice : 250 },
{ user_id : '57efb93fdc78c816a3a15c4a', totalprice : 157 },
{ user_id : '57efb93fdc78c816a3a15c4a', totalprice : 149 },
{ user_id : '57efb93fdc78c816a3a15c4a', totalprice : 104 }

我期待如下输出:

{
    user_id : '57c7f4312b3c9771219bd21c',
    finalTotal : 1262
},
{   
    user_id : '57efb93fdc78c816a3a15c4a'
    finalTotal : 660
}

【问题讨论】:

  • 好的,我来添加表格数据。

标签: node.js mongodb mongoose aggregation-framework mongodb-aggregation


【解决方案1】:

$group 运算符仅适用于聚合框架,因此您需要运行聚合管道,按 user_id 字段对文档进行分组,然后使用 @ 按聚合的 finalTotal 字段对文档进行排序987654322@ 然后使用 $limit 获取前 5 个文档。

按照此管道获得所需的结果:

Order.aggregate([
    {
        "$group": {
            "_id": "$user_id",
            "finalTotal": { "$sum": "$totalprice" }
        }
    },
    { "$sort": { "finalTotal": -1 } },
    { "$limit": 5 }
]).exec(function(error, fetchAllTopUsers){
    console.log('##################');
    console.log(fetchAllTopUsers);
});

【讨论】:

  • 感谢您的回复。我需要按 user_id 对总价格求和。比如 pritesh 做 100 个订单,总价是 15000,Chridam 做了 3 个订单,总价是 5000 这样
  • 以上答案有效,但以下无效。再看一次我的评论。我已经用示例进行了编辑
  • 也添加了我的数据
  • @PriteshMahajan 谢谢,更清楚了。我已经更新了我的答案,应该可以满足您的要求。
  • 这个答案工作正常,但现在我面临一个字符串问题。在 db “totalprice” 是字符串类型。所以当我得到结果“finalTotal”时总是显示为 0。不求和我的值。
【解决方案2】:

我们可以这样使用

db.getCollection('form_a').aggregate([
    {
        "$group": {
            "_id": "$Status",
            "counter": { "$sum": 1 }
            
        }
    }
])

【讨论】:

  • form_a 是集合名称
猜你喜欢
  • 2019-05-24
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 2017-03-03
相关资源
最近更新 更多