使用 $group 在 mongodb node.js 中查找

Use $group with find in mongodb node.js

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

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

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

我检查了这个例子,但他们没有使用 $group 查找。我是 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
}

$group operator is only available with the aggregation framework hence you need to run an aggregation pipeline that groups the documents by the user_id field and then sorts the documents by the aggregated finalTotal field using $sort and then get the top 5 documents using $limit.

遵循此管道以获得所需的结果:

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

我们可以这样使用

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