user2929577 user2929577 - 1 month ago 4
Node.js Question

Query where all array items are greater than a specified condition

I have a model which contains an array with dates. I'm using a

$gte
operator as a condition to query the collection where all the elements in the array of dates are
$gte
a given date.

For example I have this document:

{ dates: [
ISODate("2016-10-24T22:00:00.000+0000"),
ISODate("2017-01-16T23:00:00.000+0000")]
}


When I run this query
{dates: {$gte: new Date()}}
, it gives me the whole document as a result. But I want a result where every single array item matches my query, not just one.

Answer

You can do this by using $not and the inversion of your comparison condition:

db.test.find({dates: {$not: {$lt: new Date()}}})

So this matches docs where it's not the case that there's a dates element with a value less than the current time; in other words, all dates values are >= the current time.

Comments