【问题标题】:Building a pipeline and aggregate in Mongo在 Mongo 中构建管道和聚合
【发布时间】:2018-06-02 07:33:10
【问题描述】:

如何聚合以下文档类型集合,以在一段时间内根据每个 district_idcity_id 将所有 product_id 出售的 quantity 相加

我尝试使用$match$group的聚合函数但没有成功。

{
    "_id" : ObjectId("5b115e00a186ae19062b0714"),
    "id" : 86164014,
    "cost" : 3,
    "created_date" : "2017-04-04 21:44:14",
    "quantity" : 12,
    "bill_id" : 46736603,
    "product_id" : 24,
    "bill_date" : "2017-04-04",
    "district_id" : 75
    "city_id": 21
}

【问题讨论】:

  • SQL to Aggregation Mapping Chart。但现在你最大的问题是created_date 是一个“字符串”,而不是你真正应该在“一段时间”内使用的东西。你的第一要务应该是converting this,其余的当你尝试的时候真的没有那么难。我建议您先转换日期,然后至少尝试一下。
  • 嗨,尼尔,我已将 created_date 从字符串转换为日期,现在可以聚合。在下面的答案中找到结果
  • db.getCollection("collectionname").aggregate([ {$match: {bill_date: { $gte: ISODate("2017-04-01T00:00:00.0Z"), $lte: ISODate("2017-04-30T00:00:00.0Z") }}}, { $group: { _id: { product_id: "$product_id", district_id: "$district_id" }, 数量: { $sum: "$数量" } } } ])

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

您应该更具体地了解“一段时间内”以及我们应该考虑哪个字段,但第一部分的查询可能是这个:

db.getCollection("your collection").aggregate([
    {
        $group: {
            _id: {
                city_id: "$city_id", 
                district_id: "$district_id"
            },
            quantities: { $sum: "$quantity" }
        }
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 2019-08-01
    • 1970-01-01
    • 2022-11-23
    • 2020-04-09
    • 1970-01-01
    • 2020-12-12
    • 1970-01-01
    相关资源
    最近更新 更多