问题
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"
}
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()
}
])
It does not work.where am i doing wrong??I am new to mongodb. Thanks for any help
回答1:
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 }
}}
])
Try it here
And with the previous versions
db.collection.aggregate([
{ "$project": {
"date": { "$add": [ new Date(0), "$_id" ] }
}}
])
来源:https://stackoverflow.com/questions/50024852/how-to-convert-timestamp-to-date-in-mongodb