2016-12-05 194 views
-1

我對MongoDb非常陌生。我有一個收集訂單,其中有以下多個文件。MongoDb SUM GROUP BY WHERE

{ 
    "vendor": "amazon", 
    "date": ISODate("2016-12-05T21:10:39.100Z"), 
    "products" : [ 
        { 
         "id": NumberLong(590573), 
         "totalSold": NumberLong(59), 
         "totalCost": NumberLong(7350), 
         "variations": [ 
             { 
              "varId": NumberLong(1), 
              "totalSoldV": NumberLong(30), 
              "totalCostV": NumberLong(3000) 
             }, 
             { 
              "varId": NumberLong(2), 
              "totalSoldV": NumberLong(29), 
              "totalCostV": NumberLong(4350) 
             }, 
         ] 
        } 
    ] 
} 

所以我想實現是特定product.id我想date計算sum(totalSold)sum(totalCost)組。我一直在玩整體遊戲,但一直沒能做到。

+0

你這是什麼意思日期羣? – sergiuz

+0

@SergiuZaharie每個文檔都有一個字段日期。將有多個具有相同日期值的文檔。 – KunalC

+0

你是指同一天?檢查我的答案,看看是否適合你。 – sergiuz

回答

0
db.collection.aggregate([ 
    {$unwind: "$products"}, 
    {$match: {"products.id":NumberLong(590573) }}, 
    { 
     $group: { 
     _id: { 
      year : { "$year" : "$date" },   
      month : { "$month" : "$date" },   
      day : { "$dayOfMonth" : "$date" }, 
      hour : { "$hour" : "$date" }, 
      minute : { "$minute" : "$date" }, 
     }, 
     sumTotalSold: {$sum: "$products.totalSold"}, sumTotalCost: {$sum: "$products.totalCost"} 
    } 
    } 
]).pretty(); 

結果:

{ 
    "_id" : { 
     "year" : 2016, 
     "month" : 12, 
     "day" : 5, 
     "hour" : 21, 
     "minute" : 10 
    }, 
    "sumTotalSold" : NumberLong(79), 
    "sumTotalCost" : NumberLong(9850) 
}