2016-02-19 26 views
0

我有简单的模式是这样如何使用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 
} 

回答

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']} 
     }} 
]); 
+0

是的,我已经在蒙戈外壳尝试这样做,给了我想要的输出,但如何使用猫鼬返回文档? –

+0

@MuhammadFasalirRahman,请试用['Users.aggregate('](http://mongoosejs.com/docs/api.html#model_Model.aggregate),你可以在这个链接找到例子 – zangw