【问题标题】:MongoDB Aggregation Pipeline - get oldest document, but debouncedMongoDB 聚合管道 - 获取最旧的文档,但已去抖动
【发布时间】:2022-02-19 21:17:18
【问题描述】:

我的文件看起来像:

[ 
  { 
    value: 'Apple',
    createdAt: '2021-12-09T20:15:26.421+00:00',
  },
  { 
    value: 'Blueberry',
    createdAt: '2021-12-09T20:45:26.421+00:00',
  },
  { 
    value: 'Cranberry',
    createdAt: '2021-12-09T21:30:26.421+00:00',
  },
  { 
    value: 'Durian',
    createdAt: '2022-01-24T20:15:26.421+00:00',
  },
  { 
    value: 'Elderberry',
    createdAt: '2022-01-24T20:45:26.421+00:00',
  },
]

我想在获得最旧文档的地方进行聚合,但需要注意的是,如果在一小时内创建了另一个文档,它将使第一个文档无效,而我实际上想获取那个文档。例如,在上面我想返回Cranberry。最初选择Apple,但由于Blueberry 在一个小时内到达,请移至那个,因为CranberryBlueberry 的一个小时内到达,请选择Cranberry

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework nosql-aggregation


    【解决方案1】:

    您可以在聚合管道中执行以下操作:

    1. $sortcreatedAt
    2. $limit 获取最旧的文档
    3. $lookup 获取当前文档后面带有createdAt 的所有文档
    4. $reduce 循环结果数组;仅当当前条目在 1 小时内时才更新累加器/结果
    db.collection.aggregate([
      {
        $sort: {
          createdAt: 1
        }
      },
      {
        $limit: 1
      },
      {
        "$lookup": {
          "from": "collection",
          let: {
            current: "$createdAt"
          },
          pipeline: [
            {
              $match: {
                $expr: {
                  $gte: [
                    "$createdAt",
                    "$$current"
                  ]
                }
              }
            }
          ],
          "as": "within"
        }
      },
      {
        "$addFields": {
          "within": {
            "$reduce": {
              "input": "$within",
              "initialValue": null,
              "in": {
                "$cond": {
                  "if": {
                    $or: [
                      {
                        $eq: [
                          "$$value",
                          null
                        ]
                      },
                      {
                        $lte: [
                          {
                            "$subtract": [
                              "$$this.createdAt",
                              "$$value.createdAt"
                            ]
                          },
                          3600000
                        ]
                      }
                    ]
                  },
                  "then": "$$this",
                  "else": "$$value"
                }
              }
            }
          }
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2021-11-16
      相关资源
      最近更新 更多