首页 > 解决方案 > 如何按计算日期查找文档

问题描述

我有这个文件:

{ 
    "_id" : BinData(0, "RUBR58qePxvfGqR7WjpkiQ=="), 
    "creation_date" : ISODate("2020-02-05T18:30:14.152+0000"), 
    "retention" : NumberInt(24)
}

我想找到所有文件creation_date < (mygivendate) + retention

为什么当我这样做

db.getCollection("test").find({
  "creation_date":{
    "$gte":{
      "$inc":[ISODate("2010-09-18T16:27:07.000+0000"),"retention"]
    }
  }
})

它什么也没给我?

标签: mongodbmongodb-query

解决方案


$inc是更新运算符,因此不能用于查找文档。见文档

我不知道你想要达到什么目的。

但这里有一个$inc在你的数据上使用的例子

db.collection.update({
  "creation_date": {
    "$gte": ISODate("2020-02-04")
  }
},
{
  "$inc": {
    "retention": 1
  }
})

在这里试试


在哪里找到您的文件creation_date < (mygivendate) + retention

你可以做 :

db.collection.find({
  "$expr": {
    "$gte": [
      "$creation_date",
      {
        "$add": [
          ISODate("2020-01-05"),
          "$retention"
        ]
      }
    ]
  }
})

在这里试试

$expr是一个 mongo 运算符,允许您在查找查询中使用聚合表达式。所以在这里我添加一个日期$retention,看看它是否大于$creation_date


推荐阅读