如何使用Mongoose sum操作?

时间:2016-02-19 09:25:18

标签: node.js mongodb mongoose

我有像这样的简单架构

{
    "productName": "pppppp"
    "sku" : {
        "carted" : [
            {
                "_id" : ObjectId("56c6d606c0987668109a21f7"), 
                "timestamp" : ISODate("2016-02-19T08:44:54.043+0000"), 
                "cartId" : "56c6c1fd60c4491c157e433d", 
                "qty" : NumberInt(2)
            }, 
            {
                "_id" : ObjectId("56c6d653172fb54817ec2356"), 
                "timestamp" : ISODate("2016-02-19T08:46:11.902+0000"), 
                "cartId" : "56c6c1fd60c4491c157e433d", 
                "qty" : NumberInt(2)
            }, 
            {
                "_id" : ObjectId("56c6d6a7172fb54817ec2358"), 
                "timestamp" : ISODate("2016-02-19T08:47:35.652+0000"), 
                "cartId" : "56c6c1fd60c4491c157e433d", 
                "qty" : NumberInt(2)
            }
        ], 
        "qty" : NumberInt(14)
    }
}

如何查看产品" pppppp"并显示数量为20? sku.quantity添加了所有可用的sku.carted.qty。

我希望它看起来像这样

{
    "productName": "pppppp"
    "qty" : 20
}

1 个答案:

答案 0 :(得分:0)

请尝试使用$group$sum$add

> db.collection.aggregate([
       {$unwind: '$sku.carted'}, 
       // sum the `qty` in the carted array, put this result to `qt`
       {$group: {
              _id: {productName: '$productName', q: '$sku.qty'},
              qt: {$sum: '$sku.carted.qty'}
       }}, 
       // add the `qt` and `sku.qty`
       // and reshape the output result.
       {$project: {
              _id: 0, 
              productName: '$_id.productName', 
              qty: {$add: ['$_id.q', '$qt']}
       }}
]);