2016-02-19 27 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