$dayOfYear
返回日期在当年的那一天,值的范围1~366。
语法
{ $dayOfYear: <dateExpression> }
参数说明:
<dateExpression>
为可被解析为Date、Timestamp或ObjectID的表达式<dateExpression>
也可以是一个文档{ date: <dateExpression>, timezone: <tzExpression> }
date
是可以被解析为Date、Timestamp或ObjectID的表达式timezone
可选,操作结果的时区
使用
下面通过示例对使用规则进行说明:
例1
{ $dayOfYear: new Date("2016-01-01") }
结果:1
例2
{ $dayOfYear: { date: new Date("Jan 7, 2003") } }
结果:7
例3
{ $dayOfYear: {
date: new Date("August 14, 2011"),
timezone: "America/Chicago"
} }
结果:226
例4
{ $dayOfYear: ISODate("1998-11-07T00:00:00Z") }
结果:311
例5
{ $dayOfYear: {
date: ISODate("1998-11-07T00:00:00Z"),
timezone: "-0400"
} }
结果:310
例6
{ $dayOfYear: "March 28, 1976" }
结果:error
例7
{ $dayOfYear: Date("2016-01-01") }
结果:error
例8
{ $dayOfYear: "2009-04-09" }
结果:error
举例
sales
集合有下面的文档:
{
"_id" : 1,
"item" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-01-01T08:15:39.736Z")
}
下面的聚合使用$dayOfYear
和其他日期运算符来分解日期字段:
db.sales.aggregate(
[
{
$project:
{
year: { $year: "$date" },
month: { $month: "$date" },
day: { $dayOfYear: "$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
}