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));
});
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
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" ]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With