具有数组和和$ lookup sum的mongo聚合

时间:2017-07-09 15:18:33

标签: mongodb

发票表

{ 
    "_id" : 123
    "dueDate" : 1494858422, 
    "invoiceLines" : [
        {
            "lineText" : "Rent Price", 
            "amountTotal" : 5000
        }, 
        {
            "lineText" : "Discount", 
            "amountTotal" : -1000
        }, 
        {
            "lineText" : "Final cleaning", 
            "amountTotal" : 500
        } 
    ], 
    "paid" : false
}

收据表

{ 
    "_id" : 20,
    "invoiceNo" : 123,
    "amount" : 2000
},
{ 
    "_id" : 21,
    "invoiceNo" : 123,
    "amount" : 1000 
}

我想要的结果

{
    "_id" : 123,
    "dueDate" : 1494858422,
    "invoiceTotal" : 4500,
    "receiptTotal" : 3000
}

所以我想将所有invoiceLines.amountTotal添加到一起,获取所有receipts并同时添加amount

问题是结果显示invoiceTotal: 0

这是我的汇总:

db.getCollection('invoice').aggregate([
{
    $match: {
        "dueDate"  : {$lte: (1498988330)},
        "paid" : false
    }
},
{
    $lookup: {
        from: "receipt",
        localField: "_id",
        foreignField: "invoiceNo",
        as: "receipt"
    }
},
{
    $project:{
        "_id": 1,
        "dueDate": 1,
        "invoiceTotal": {
            "$sum": {
                "$map": {
                    "input": "$invoice.invoiceLines",
                    "as": "il",
                    "in": "$$il.amountTotal"
                }
            }
        },
        "receiptTotal": {
            "$sum": {
                "$map": {
                    "input": "$receipt",
                    "as": "re",
                    "in": "$$re.amount"
                }
            }
        }
    }
}])

我试过

{
    $unwind: "$invoice.invoiceLines" 
}, 

但是后来我根本没有得到任何结果。

0 个答案:

没有答案