0

My goal is to find objects in my database where the difference between the date in the date field and the current date is greater than the value of the interval field.

My objects in the database look like this with a few more fields

[{
"date": {
  "$date": "2022-02-04T12:00:00Z"
},
"interval": 5
},{
"date": {
  "$date": "2022-02-04T12:00:00Z"
},
"interval": 60
}]

So if it would be 2022-02-04T12:30:00Z right now my query is supposed to return the first entry only, as only there the difference between the date and and the current date is greater than 5 minutes.

With a fix date in the query this is fairly easy: {date: {$gte: ISODate('2022-02-04T12:30:00Z')}}.

With info from here, here and here I came up with this query:

db.articles.aggregate([{$project: {result: {$filter: {input: "$interval" as "interval", cond: {$gte : new Date(ISODate().getTime()-1000* interval)}}}}}])

Sadly it's not valid and throws a SyntaxError, but I don't know what to do. Since I have done very little with mongodb so far, I am getting nowhere.

How can I subtract the value of the interval field from the current date to use that in my query?

M..
  • 75
  • 1
  • 3
  • 11
  • `input: "$interval"` - there needs to be a comma (`,`) after that piece of code; that is a reason for the syntax error. – prasad_ Feb 07 '22 at 05:34
  • @prasad_ Then there is the next SyntaxError `Unexpected token, expected ","` pointing at the first quotation mark from `, as "interval",`. Is this even the correct approach? – M.. Feb 07 '22 at 17:27
  • Also, see the usage / syntax of [$gte](https://docs.mongodb.com/manual/reference/operator/aggregation/gte/) aggregation operator - your query doesn't use it correctly. – prasad_ Feb 07 '22 at 17:35

0 Answers0