【问题标题】:MongoDB find all documents where field 1 is seven days or more after field 2MongoDB 查找字段 1 在字段 2 之后 7 天或更长时间的所有文档
【发布时间】:2022-02-01 11:30:19
【问题描述】:

我需要搜索一个大型 mongo 集合并找到所有在 createdAt 后至少 7 天更新的文档。

我的数据基本上是这样的:

"createdAt" : ISODate("2021-04-03T10:17:21.256Z"),
"updatedAt" : ISODate("2021-04-03T10:17:21.256Z")

我将不胜感激。

【问题讨论】:

    标签: mongodb robo3t


    【解决方案1】:

    在匹配中使用$expr$dateAdd 仅在 mongodb 5.0 中可用。

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $gt: [
              "$updatedAt",
              {
                $dateAdd: {
                  startDate: "$createdAt",
                  unit: "day",
                  amount: 7
                }
              }
            ]
          }
        }
      }
    ])
    

    mongoplayground


    在匹配中使用$expr$add.

    604800000 = 7 * 24 * 60 * 60 * 1000

    db.collection.aggregate([
      {
        "$match": {
          $expr: {
            $gt: [
              "$updatedAt",
              {
                $add: [
                  "$createdAt",
                  604800000
                ]
              }
            ]
          }
        }
      }
    ])
    

    mongoplayground


    使用$where

    db.collection.find({
      "$where": "this.updatedAt > new Date(this.createdAt.getTime() + 604800000)"
    })
    

    mongoplayground

    【讨论】:

    • 非常感谢您的回答。看起来我们使用的是旧版本的 Mongo,所以我会根据您的回答看看我能做些什么。我很感激。
    • @jrdhawk 我用$add更新我的答案
    • 非常感谢您的帮助。我还是有一些麻烦。看起来我们使用的是 Mongo 3.6.0。我不断收到:无法执行脚本。错误:未捕获的异常:错误:命令失败:{“ok”:0,“code”:303,“errmsg”:“Feature not supported”}:聚合失败:_getErrorWithCode@src/mongo/shell/utils.js:25 :13
    • @jrdhawk 我认为 $expr$gt$add 在 mongodb 3.6 中可用
    • @jrdhawk 我用$where更新我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多