Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert timestamp to ISO date in mongodb aggregate

I am using node.js mongodb client. I have a timestamp value in a collection, now I want to use aggregate to convert timestamp to IOSDate, so I can compare it easily. But I do not know how to do it.

   var db = game.getDB();
    var coll = db.collection("LoginRecord");
    coll.aggregate([
        {
            $project: {
                "PT" : 1,
                "PID" : 1,
                "regDate" : new Date("$createTime"), //#####createTime is a timestamp, I want to convert it to IOSDate
                "loginDay" : { $dayOfYear : "$_serverDate"}
            }
        },
        {
            $group : {
                "_id" : "$loginDay",
                "logUsers" : { $addToSet: "$PID"}
            }
        },
        {
            $unwind : "$logUsers"
        },
        {
            "$group" : {
                "_id" : "$_id",
                "logCount" : { $sum: 1}
            }
        }
    ], function(err, res) {
        logger.info("aggregate res " + JSON.stringify(res));
    });
like image 241
user3172936 Avatar asked Jan 09 '23 00:01

user3172936


2 Answers

Mongodb 4.0 has introduced $toDate aggregation which simply convert timestamp to ISO date

db.collection.aggregate([
  { "$project": {
    "regDate": { "$toDate": "$createTime" }
  }}
])

You can try it here

like image 53
Ashh Avatar answered Jan 11 '23 13:01

Ashh


As referred convert milliseconds to date in mongodb aggregation pipeline for group by?

You can do it as follows to convert milliseconds (timestamp) to date object:

"regDate": {
   $add: [ new Date(0), "$createTime" ]
}
like image 45
prog.Dusan Avatar answered Jan 11 '23 13:01

prog.Dusan