首页 > 解决方案 > 在MongoDB中以字符串格式的日期按月和年分组

问题描述

我收藏的日期是字符串格式。我正在尝试按月和年对值进行分组。我试过$toDate$dateFromString. 当我尝试$monthand$year时,我会得到一些1月份和随机年份的年份。

我不知道接下来我应该做什么。如何按月和年分组?

这是我的代码:

db.hb_data.aggregate([{
$match: {
    date: {$exists: true}
}
}, {
    $group: {
        _id: {date: "$date"},
        video_starts:{$sum: '$video_starts'}
    }
}, {
    $project: {
        month: { $month: new Date("$_id.date") } ,
        year: { year: new Date("$_id.date") } ,
        date: "$_id.date",
        video_starts: '$video_starts'
}   }
])

这是我的结果:

我的结果

当我的日期为字符串格式时,如何按月和年获得总和?

标签: mongodbdategroup-byaggregatepymongo

解决方案


假设这是数据集。

[
  {"Id_Cust": "4145","firstName": "Albade","lastName": "Maazou", "gender": "female","date": "21/03/1981"},
  {"Id_Cust": "5296", "firstName": "Rafael","lastName": "Oliveira","gender": "male","date": "08/06/1987"},
  {"Id_Cust": "6192","firstName": "Abdul Rahman","lastName": "Budjana","gender": "male","date": "26/01/1990"}
]

您可以通过$dateFromString以下方式使用它:

db.collection.aggregate([
  {
    $project: {
      month: {
        $month: {
          $dateFromString: {
            dateString: "$date",
            format: "%d/%m/%Y"
          }
        }
      },
      year: {
        $year: {
          $dateFromString: {
            dateString: "$date",
            format: "%d/%m/%Y"
          }
        }
      }
    }
  },

])

输出:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "month": 3,
    "year": 1981
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "month": 6,
    "year": 1987
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "month": 1,
    "year": 1990
  }
]

更新

您也可以使用$toDate但您的字符串日期格式应该是 "yyyy-mm-dd"格式,例如{$toDate: "2018-03-03"}

db.collection.aggregate([
  {
    $project: {
      month: {
        $month: {
          $toDate: "$date"
        }
      },
      year: {
        $year: {
          $toDate: "$date"
        }
      }
    }
  }
])

它提供与上面完全相同的输出,但请确保您的字符串日期是"yyyy-mm-dd"这种格式。


推荐阅读