I have a Mongo collection that looks as follows:
[{
id: 1,
timestamp: 1534488870841,
type: \'deposit\'
}, {
id: 1,
timestamp: 15344889151
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"
}
}}
])