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