【问题标题】:MongoDb SUM GROUP BY WHEREMongoDb SUM GROUP BY WHERE
【发布时间】:2016-12-05 22:52:46
【问题描述】:

我对 MongoDb 很陌生。我有一个集合订单,其中包含多个文档,如下所示。

{
    "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) 组。我一直在玩聚合,但一直没能做到。

【问题讨论】:

  • 按日期分组是什么意思?
  • @SergiuZaharie 每个文档都有一个字段日期。会有多个文档具有相同的日期值。
  • 你是说同一天?检查我的答案,看看是否适合你。
  • 实际上是同一分钟:)
  • 另外,这将给我所有产品的总和。如何获得特定产品 ID 的总和。

标签: arrays mongodb mongodb-query


【解决方案1】:
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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多