In MongoDB, how to convert seconds after epoch to Datetimes?

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

I am looking for the equivalent of the following Python function

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

      

I understand that it would be better to just insert data directly, unfortunately this is not my situation.

Specifically, I am using a pipelined aggregation query system, so whatever fits into this structure is preferable.

+3


source to share


1 answer


The arithmetic operators of the aggregation structure can handle conversion.
(performed on a mango 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 is like:

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

      

+6


source







All Articles