MongoDb SUM GROUP BY WHERE

时间:2016-12-05 22:52:47

标签: arrays mongodb mongodb-query

我是MongoDb的新手。我有一个集合Order,它有多个文件如下。

{
    "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特定sum(totalSold)我要按sum(totalCost)计算date DoubleAnimation doubleAnimationCanvasLeft = new DoubleAnimation(); doubleAnimationCanvasLeft.From = Canvas.GetLeft(aDiceToBeChecked.myGrid); doubleAnimationCanvasLeft.To = Canvas.GetLeft(aDiceToBeChecked.myGrid) - 102; doubleAnimationCanvasLeft.Duration = TimeSpan.FromMilliseconds(myTimespan); doubleAnimationCanvasLeft.FillBehavior = FillBehavior.HoldEnd; Storyboard storyboardCanvasLeft = new Storyboard(); storyboardCanvasLeft.Children.Add(doubleAnimationCanvasLeft); Storyboard.SetTarget(storyboardCanvasLeft, aDiceToBeChecked.myGrid); Storyboard.SetTargetProperty(storyboardCanvasLeft, "(Canvas.Left)"); storyboardCanvasLeft.Begin(); 组。我一直在玩聚合但是却无法这样做。

1 个答案:

答案 0 :(得分: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)
}