猫鼬中groupBy后的总和

Sum after groupBy in mongoose

我在 mongodb 中有一个这样的文档

{
"_id" : ObjectId("5552f1ea3726845811c33ffe"),
"date" : "13-05-2015",
"User" : 107,
"allRecipt" : [ 
    {
        "recipt_Number" : 1,
        "amount" : 123,
        "_id" : ObjectId("5552f1ea3726845811c34000")
    }, 
    {
        "recipt_Number" : 2,
        "amount" : 566,
        "_id" : ObjectId("5552f1ea3726845811c33fff")
    }
],
"__v" : 0
}

另一个文件

 {
"_id" : ObjectId("5552f24d3726845811c34003"),
"date" : "13-05-2015",
"User" : 108,
"allRecipt" : [ 
    {
        "recipt_Number" : 1,
        "amount" : 2345,
        "_id" : ObjectId("5552f24d3726845811c34005")
    }, 
    {
        "recipt_Number" : 2,
        "amount" : 800,
        "_id" : ObjectId("5552f24d3726845811c34004")
    }
],
"__v" : 0
}

第 3 个文档

   {
"_id" : ObjectId("5552f24d3726845811c34003"),
"date" : "13-05-2015",
"User" : 108,
"allRecipt" : [ 
    {
        "recipt_Number" : 1,
        "amount" : 200,
        "_id" : ObjectId("5552f24d3726845811c34005")
    } 
],
"__v" : 0
}

我想在这里做的是将文档与请求的日期进行匹配,然后按具有相同 "User" 字段的文档分组,然后得到 amount.I 的每个用户的总计使用了这样的查询:

Recipt.aggregate([
        {$match: {'date': req.params.date}},
        {
            $group:{
                _id : "$User",
                "total": { 
                    "$sum": "$allRecipt.amount" 
                } 
            }
        }

    ], function (err, result){
        if(err){
            console.log(err);
            return;
        }
        console.log(result);
        res.json(result);
    });

正在按用户分组但显示总数:0 结果:

     [{_id:108, total:0},{_id:107, total:0}]

但我想要的是

     for 108 total be 2345+800+200  and for 107 total be 123+566

更新

对于较新的 MongoDB 版本:

const pipeline = [
    { "$match": { "date": "13-05-2015" } },
    { "$addFields": {
        "total": { "$sum": "$allRecipt.amount" }
    } },
    { "$group":{
        "_id" : "$User",
        "total": { 
            "$sum": "$total" 
        } 
    } }
];

您需要对 separated/deconstructed 个文档进行 $unwind operator pipeline stage after the match pipeline step as it deconstructs the allRecipt array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element. You can then do the $group 操作,以获取按 User 键分组的文档的总收款金额:

var pipeline = [
    { "$match": { "date": "13-05-2015" } },
    { "$unwind": "$allRecipt" },
    { "$group":{
        "_id" : "$User",
        "total": { 
            "$sum": "$allRecipt.amount" 
        } 
    } }
];

Recipt.aggregate(pipeline)
      .exec(function (err, result){
          if(err){
              console.log(err);
              return;
          }
          console.log(result);
          res.json(result);
    });