How to convert date format in mongodb

19,829

Solution 1

Mongo stores dates as ISODate objects. Just wrap our date into ISODate constructor:

{
    "fooBarDate": {
        "$lte": ISODate("2013-05-26T05:00:00.000Z")
    }
}

Solution 2

The correct data format if you pass a string into the query is ISO8601 which is looks like you have done, however you can also pass the javascript date object into the query directly and get the same result. It looks like you may be missing the proper brackets which could be causing your query to fail. Try reformatting your code in this manner (edit I am using mongoose, but I think straight mongo is the same):

var currentTime = new Date;
orm.Records.find({lastUpdate:{$lte:currentTime}})
Share:
19,829
callmekatootie
Author by

callmekatootie

I am a CoPilot @ Topcoder - a crowdsourcing company. I go by the handle @callmekatootie on Topcoder, Github and Twitter and most other platforms.

Updated on June 13, 2022

Comments

  • callmekatootie
    callmekatootie almost 2 years

    I am using an API (so I have no control over the fields) - one of the fields is of type Date.

    Now, I find that the date stored in the records resembles the following value:

    {
        ...
        "foobarDate": "2013-05-26T05:00:00.000Z",
        ...
    }
    

    Now I wish to retrieve some records based on this date - for example, I need to retrieve all the records whose fooBarDate is earlier than today's date.

    If I use Javascript's Date() functionality, then I get the date in the following format:
    Wed Jun 19 2013 21:13:50 GMT+0530 (IST)

    If I try to design my query as follows...

    {
        "fooBarDate": {
            "$lte": <the date calculated in javascript>
        }
    }
    

    ...I do not get the records - I get an empty array - I suspect it is due the reason that the format of the Date stored in MongoDB is different from the one I am passing.

    How to convert the Javascript date format to the mongodb format? Or at least, how do I get the current date in the format stored in MongoDB?

    P.S. I am using nodeJs and wish to query the DB in this case.