Mendes
Mendes

Reputation: 18561

Mongo query if field does not exist. If exists, must be within a range

I have a collection that has an endDateTime field:

If endDateTime is null, the operation is not yet finished. If it has finished, endDateTime contains the timestamp (Javascript Date.now())

How can I query for records that is not yet finished (endDateTime is null) or has ended in the last 24 hours:

   let endDateTime = Date.now();
   let startDateTime = endDateTime - 24 * 60 * 60 * 1000;

   query.endDateTime = {
             $or: [
                   null,
                   { $and: [{ $gte: startDateTime }, { $lte: endDateTime }] }
                  ]
    };

My query is returning registers before 24 hours ago. How to solve it?

Upvotes: 2

Views: 922

Answers (1)

mickl
mickl

Reputation: 49985

You can combine your criteria with $or:

db.col.find({
    $or: [
        { endDateTime: null },
        { endDateTime: { $gt: Date.now() - 24 * 60 * 60 * 1000 } } 
    ]
})

or if you have no endDateTime key in some of your documents then you need $exists operator:

db.col.find({
    $or: [
        { endDateTime: { $exists: false } },
        { endDateTime: { $gt: Date.now() - 24 * 60 * 60 * 1000 } } 
    ]
})

Upvotes: 2

Related Questions