问题
I have a Mongo collection that looks as follows:
[{
id: 1,
timestamp: 1534488870841,
type: 'deposit'
}, {
id: 1,
timestamp: 1534488915119,
type: 'deposit'
}]
How can I make a query to list all deposit
transactions, grouped by the month.
The month must be calculated using the timestamp
attribute (UNIX millisecond).
I can get the deposit's as follows but I am unsure on how to group:
db.getCollection('transactions').find(
{"type":"deposit"});
Edit: Mongo version 3.4
回答1:
You can try below aggregation in mongodb 4.0
You can convert timestamp
to date using $toDate aggregation and then $group with $month aggregation
db.collection.aggregate([
{ "$match": { "type": "deposits" }},
{ "$addFields": {
"date": {
"$toDate": "$timestamp"
}
}},
{ "$group": {
"_id": { "$month": "$date" },
"deposits": {
"$push": "$$ROOT"
}
}}
])
You can try below aggregation in mongodb 3.4
In 3.4 you can convert timestamp
to date by adding new Date()
in it and $group it by using $dateToString aggregation
db.collection.aggregate([
{ "$match": { "type": "deposits" }},
{ "$addFields": {
"date": {
"$add": [ new Date(0), "$timestamp" ]
}
}},
{ "$group": {
"_id": {
"$dateToString": {
"format": "%m",
"date": "$date"
}
},
"deposits": {
"$push": "$$ROOT"
}
}}
])
来源:https://stackoverflow.com/questions/51889949/mongo-groupby-month-using-unix-millisecond-time