mongodb 在mongo查询中将iso日期转换为时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39274311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert iso date to timestamp in mongo query
提问by nirvair
here is the query
这是查询
[
{
"$project": {
"formattedDate": {
"$dateToString": { "format": "%Y-%m-%d", "date": "$ceatedAt" }
},
"createdAtMonth": { "$month": "$ceatedAt" },
"rating": 1
}
},
{
"$group": {
"_id": "$formattedDate",
"average": { "$avg": "$rating" },
"month": { "$first": "$createdAtMonth" },
}
}
]
I need the date in timestamp. How to do that?
我需要时间戳中的日期。怎么做?
回答by tarashypka
Use $subtract
arithmetic aggregation operatorwith your Date as minuendand new Date("1970-01-01")
as subtrahend.
使用算术集成算你的日期作为被减数,并作为减数。$subtract
new Date("1970-01-01")
db.collection.aggregate(
{
$project: { "timestamp": { $subtract: [ "$createdAt", new Date("1970-01-01") ] } }
}
);
For document
对于文件
{ "_id": 1, "createdAt": ISODate("2016-09-01T14:35:14.952Z") }
the result is
结果是
{ "_id": 1, "timestamp": NumberLong("1472740514952") }
If you want to group both by timestamp and (year, month, date) you can divide timestamp by the amount of milliseconds in a day, so that it will be unique for each day (and not for each millisecond)
如果您想同时按时间戳和(年、月、日)分组,您可以将时间戳除以一天中的毫秒数,以便每天(而不是每毫秒)都是唯一的
db.collection.aggregate(
{
$project:
{
"timestampByDay":
{
$floor:
{
$divide:
[
{ $subtract: [ "$createdAt", new Date("1970-01-01") ] },
24 * 60 * 60 * 1000
]
}
},
"date": "$createdAt"
}
},
{
$group:
{
"_id": "$timestampByDay",
"date": { $first: "$date" }
}
}
);