如何在mongodb中将时间戳转换为日期? [英] how to convert timestamp to date in mongodb?
问题描述
我正在进行mongodb集合的聚合.我的mongodb集合在时间戳中具有creation_time.如何收集当天的结果并与第二天的结果进行聚合?假设我必须收集5天的数据.我的mongodb集合是:
i am working on aggregation of mongodb collection.my mongodb collection has creation_time in timestamp.How will i can collect same day result and aggregate with next day result.Suppose i have to collect data for 5 days.My mongodb collection is:
{
"_id" : "1522845653126"
},
{
"_id" : "1522838153324"
},
{
"_id" : "1513421466415"
},
{
"_id" : "1515488183153"
},
{
"_id" : "1521571234500"
}
我该如何计算.在特定日期保存了多少项? nd假设我要查询的结果返回聚合的运行总计,例如:
How can i calculate.How many entry are save on specific date?? nd suppose I want is to query results that returns a running total of the aggregation, like:
{
time: "2013-10-10"
count: 3,
},
{
time: "2013-10-11"
total: 7,
}
类似的东西. 我试图做这样的事情
something like this. i have tried to do something like this
db.coll.aggregate([
{
$group:{
_id:new Date($creation_time).toLocaleDateString(),
$count:{$add:1}
}
time:new Date($creation_time).toLocaleDateString()
}
])
它不起作用.我在哪里做错了?我是mongodb的新手. 感谢您的帮助
It does not work.where am i doing wrong??I am new to mongodb. Thanks for any help
推荐答案
您可以使用 $toLong
将 mongodb 3.6
You can use $toDate
aggregation to convert timestamp to ISO date and $toLong
to convert string timestamp to integer value in mongodb 3.6
db.collection.aggregate([
{ "$project": {
"_id": {
"$toDate": {
"$toLong": "$_id"
}
}
}},
{ "$group": {
"_id": { "$dateToString": { "format": "%Y-%m-%d", "date": "$_id" } },
"count": { "$sum": 1 }
}}
])
尝试> 此处
以及以前的版本
db.collection.aggregate([
{ "$project": {
"date": { "$add": [ new Date(0), "$_id" ] }
}}
])
这篇关于如何在mongodb中将时间戳转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!