How to group documents by month in mongodb?

I have transaction data collection in mongodb, for example:

[
   {timestamp: ISODate("2015-11-10T11:33:41.075Z"), nominal: 25.121},
   {timestamp: ISODate("2015-11-22T11:33:41.075Z"), nominal: 25.121},
   {timestamp: ISODate("2015-11-23T11:33:41.075Z"), nominal: 26.121},
   {timestamp: ISODate("2015-12-03T11:33:41.075Z"), nominal: 30.121},
]

How can I use mongodb () aggregation to calculate my total transaction every month? I tried to use

db.getCollection('transaction').aggregate([
  { $group: {_id: "$timestamp", total: {$sum: "$nominal"} } }
])

Failed, as I used timestampinstead month. I do not want to add another field for monthto the transaction data. I am thinking of a custom function for the $ group pipeline that returns the month value. Is it possible? if so, how?

+4
source share
1 answer

You need a preliminary $projectstage in which you use $monthto return the "month".

 db.transaction.aggregate([
    { "$project": {
        "nominal": 1, 
        "month": { "$month": "$timestamp" }
    }}, 
    { "$group": {
        "_id": "$month", 
        "total": { "$sum": "$nominal" }
    }}
])

:

{ "_id" : 12, "total" : 30.121 }
{ "_id" : 11, "total" : 76.363 }
+3

Source: https://habr.com/ru/post/1617694/


All Articles