$year(聚合)
定义
行为
例子 | 结果 | ||||
---|---|---|---|---|---|
| 2016 | ||||
| 2003 | ||||
| 2011 | ||||
| 1998 | ||||
| 1998 | ||||
| error | ||||
| error | ||||
| error |
注意
$year 不支持将字符串作为参数。
例子
请考虑包含以下文档的 sales
集合:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:15:39.736Z") }
以下聚合使用 $year
和其他日期操作符来拆分 date
字段:
db.sales.aggregate( [ { $project: { year: { $year: "$date" }, month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, hour: { $hour: "$date" }, minutes: { $minute: "$date" }, seconds: { $second: "$date" }, milliseconds: { $millisecond: "$date" }, dayOfYear: { $dayOfYear: "$date" }, dayOfWeek: { $dayOfWeek: "$date" }, week: { $week: "$date" } } } ] )
操作返回以下结果:
{ "_id" : 1, "year" : 2014, "month" : 1, "day" : 1, "hour" : 8, "minutes" : 15, "seconds" : 39, "milliseconds" : 736, "dayOfYear" : 1, "dayOfWeek" : 4, "week" : 0 }