Search code examples
datemongodbtalend

Date limiting query for MongoDB


I'm looking to do an extract from a MongoDB from a particular date. Since I'm using a component in Talend that sends the query I'm kind of limited in the sense that I can't use multiple lines of code.

Can you do a date limitation directly in the find-method?

db.example.find({ ts: { $gt: lowdate} });

Where lowdate is substituted for something that I hope any of you can figure out.

Many thanks!

PS. The date format in the mongodb, if that matters, is "Dec 16, 2011 7:37:06 PM".

--- Update --- From my MongoDB:

, "ty" : "auth", "ts" : "Dec 16, 2011 3:28:01 PM",

which suggests the format of the timestamp (ts) is a string. Correct?


Solution

  • If the date is stored as a string in that format, you will not be able to make a query. In order to fix this, I suggest you write a script in your favourite language that scans all the documents and convert this date-as-a-string into a timestamp. You can either overwrite the "ts" field, or create a new one, f.e. something called "ts_int".

    For example, in PHP you would do:

    <?php
    $m = new Mongo();
    $c = $m->mydbname->example;
    
    foreach ( $c->find() as $item )
    {
        $item['ts_int'] = strtotime( $item['ts'] );
        $c->update( $item );
    }
    ?>