sumowrestler
sumowrestler

Reputation: 365

How to compare dates in Mongo query

I am trying to get the Mongo database to return all of the records created within the past week. Each record has a field 'created at' which will be something like '6/22/17 09:14'. How do I check if this date occurred in the past week?

I have some code that looks like this:

the_collection.find({ALERT_CREATED : {&gt : new Date() - ONE_WEEK}}).toArray(function(error, results) {
    if (error) {
        callback(error);
    } else {
        callback(null, results);
    }
});

With the different date formats, the two dates can't be compared.

UPDATE:
To clarify the issue, the dates in the database have the form 6/22/17 09:14 and as such cannot be compared correctly against a Date() object. Is there any way to compare them correctly?

Upvotes: 0

Views: 6214

Answers (3)

Manuel
Manuel

Reputation: 15042

The date does not seem to be a standardized format. You would have to manually convert the given string into a valid date string.

One way is splitting up your string and using dateFormParts as documented here to construct a date.

{
    $dateFromParts : {
        'year': <year>, 'month': <month>, 'day': <day>,
        'hour': <hour>, 'minute': <minute>, 'second': <second>,
        'milliseconds': <ms>, 'timezone': <tzExpression>
    }
}

Upvotes: 0

Chava Geldzahler
Chava Geldzahler

Reputation: 3730

First you need the date to compare the created_at field to (today - 7), in MongoDB's date format. Then get only dates that come after.

var lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() -7);

db.the_collection.find({'created_at': {'$gte': lastWeek}});

Upvotes: 2

Toan Tran
Toan Tran

Reputation: 2047

You may need to subtract days in MongoDB query. Please try below code:

   the_collection.find(
   {
       "ALERT_CREATED": 
       {
           $gte: (new Date((new Date()).getTime() - (7 * 24 * 60 * 60 * 1000)))
       }
   })

   1 day = 1*24*60*60000 = 1 x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds

Upvotes: 2

Related Questions