Mongo groupby month using UNIX millisecond time

房东的猫 提交于 2019-12-20 03:16:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!