groupofy在猫鼬之后的总和

时间:2015-05-13 07:14:33

标签: mongodb 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
}

我想在这里做的是将文档与请求的日期进行匹配,然后按具有相同“用户”字段的文档进行分组,然后为每个金额用户获取总数。我使用了这样的查询:

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

1 个答案:

答案 0 :(得分:3)

您需要在匹配管道步骤之后包含$unwind运算符管道阶段,因为它会从输入文档中解构User数组字段,以便为每个元素输出文档。每个输出文档都是输入文档,其中数组字段的值由元素替换。然后,您可以对分离/解构的文档执行$group操作,以获取按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); }); 键分组的文档的总收据金额:

ContentDefinitionManager.AlterPartDefinition("Faq",
           cfg => cfg
               .Attachable()
               .WithField("Question", f => f
                   .OfType("TextField")
                   .WithDisplayName("Question")
                   .WithSetting("Flavor","Wide"))
               .WithField("Answer", f => f
                   .OfType("TextField")
                   .WithDisplayName("Answer")
                   .WithSetting("Flavor", "Html"))