MRocklin
MRocklin

Reputation: 57281

In MongoDB how do I convert seconds after epoch to Datetimes?

In MongoDB how do I convert seconds after epoch to Datetimes in a query?

I'm looking for the equivalent to the following Python function

In [10]: datetime.utcfromtimestamp(1000000000)
Out[10]: datetime.datetime(2001, 9, 9, 1, 46, 40)

I understand that it would have been nicer to just insert datetimes directly, sadly that isn't my situation.

In particular I'm using the aggregation pipeline query system, so something that fits neatly into that framework is preferable.

Upvotes: 4

Views: 8154

Answers (1)

Wizard
Wizard

Reputation: 4421

The arithmetic operators of aggregation framework are able to handle the conversion.
(run on mongo shell)

// initialize for test
var date = new Date();
date.setMilliseconds(0);
var epochSeconds = date.getTime() / 1000;
db.c.insert({date : date, epochSeconds : epochSeconds});

// perform test
var baseDate = new Date(0);
db.c.aggregate([{
    $project: {
        date : 1, 
        newDate : {
            $add : [ baseDate, {
                $multiply : [ "$epochSeconds", 1000 ]
            }]
        }
    }
}, 
// optional, just for easier to determine
{
    $project : {
        date : 1,
        newDate : 1,
        comparison : {
            $cond : {
                "if" : {
                    $eq : [ "$date", "$newDate" ]
                },
                "then" : "equal",
                "else" : "not equal"
            }
        }
    }
}]).pretty();

And the output like:

{
    "_id" : ObjectId("545460af6e66646769ae0a9d"),
    "date" : ISODate("2014-11-01T04:25:18Z"),
    "newDate" : ISODate("2014-11-01T04:25:18Z"),
    "comparison" : "equal"
}

Upvotes: 6

Related Questions