zeus
zeus

Reputation: 12975

How to find document by calculated date

I have this document :

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

I want to find all documents where creation_date < (mygivendate) + retention

Why when I do

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

it returns me nothing ?

Upvotes: 1

Views: 63

Answers (1)

AlexisG
AlexisG

Reputation: 2484

$inc is an update operator and therefore can't be used to find documents. See the doc

I don't know what you are trying to achieve.

But here is an example of the use of $inc on your data

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

try it here


To find your documents where creation_date < (mygivendate) + retention

You can do :

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

Try it here

$expr is a mongo operator that allows you to use aggregation expression in find queries. So here I add a date with $retention, and see if it's greater than $creation_date

Upvotes: 1

Related Questions