Mongo groupby month using UNIX millisecond time

前端 未结 1 1639
悲哀的现实
悲哀的现实 2020-12-21 11:27

I have a Mongo collection that looks as follows:

[{
    id: 1,
    timestamp: 1534488870841,
    type: \'deposit\'
}, {
    id: 1,
    timestamp: 15344889151         


        
相关标签:
1条回答
  • 2020-12-21 12:05

    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"
        }
      }}
    ])
    
    0 讨论(0)
提交回复
热议问题