定义
- $dateToString
- 根据用户指定的格式将日期对象转换为字符串。 - $dateToString表达式采用以下操作符表达式语法:
可以使用 $dateToString 查找托管在以下环境中的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务 
- MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本 
- MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本 
$dateToString 表达式采用以下操作符表达式语法:
{ $dateToString: {     date: <dateExpression>,     format: <formatString>,     timezone: <tzExpression>,     onNull: <expression> } } 
| 字段 | 说明 | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 
 | |||||||||||||
| 
 | 可选。 日期格式规范。  如果未指定,且指定了  如果未指定,且  | ||||||||||||
| 
 | 可选。操作结果的时区。 
 | ||||||||||||
| 
 | 可选。当  
 | 
格式描述符
<formatString> 中可使用以下格式说明符:
| 说明符 | 说明 | Possible Values | 
|---|---|---|
| 
 | 缩写月份名称(3 个字母) 7.0 版本中的新增功能。 | 
 | 
| 
 | 完整月份名称 7.0 版本中的新增功能。 | 
 | 
| 
 | 月中的某一天(2 位数字,补零) | 
 | 
| 
 | ISO 8601 格式的年份 | 
 | 
| 
 | 小时(2 位数字,填充零,24 小时时钟) | 
 | 
| 
 | 年月日(3 位数字,填充零) | 
 | 
| 
 | 毫秒(3 位数字,填充零) | 
 | 
| 
 | 月份(2 位数字,补零) | 
 | 
| 
 | 分钟(2 位数字,填充零) | 
 | 
| 
 | 第二(2 位数字,补零) | 
 | 
| 
 | 一周中每天的编号(采用 ISO 8601 格式,1-星期一,7-星期日) | 
 | 
| 
 | 年中的某一周(2 位数字,补零) | 
 | 
| 
 | ISO 8601 格式的年中的某一周 | 
 | 
| 
 | 周中的某一天(1-星期日,7-星期六) | 
 | 
| 
 | 年份(4 位数字,补零) | 
 | 
| 
 | 与 UTC 的时区偏移。 | 
 | 
| 
 | 从 UTC 开始偏移的分钟数。例如,如果时区偏移 ( | 
 | 
| 
 | 作为文本的百分比字符 | 
 | 
例子
使用以下文档创建 sales 集合:
 db.sales.insertOne(   {    "_id" : 1,    "item" : "abc",    "price" : 10,    "quantity" : 2,    "date" : ISODate("2014-01-01T08:15:39.736Z")   } ) 
以下聚合使用$dateToString将date字段作为格式化字符串返回:
db.sales.aggregate(    [      {        $project: {           yearMonthDayUTC: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },           timewithOffsetNY: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "America/New_York"} },           timewithOffset430: { $dateToString: { format: "%H:%M:%S:%L%z", date: "$date", timezone: "+04:30" } },           minutesOffsetNY: { $dateToString: { format: "%Z", date: "$date", timezone: "America/New_York" } },           minutesOffset430: { $dateToString: { format: "%Z", date: "$date", timezone: "+04:30" } },           abbreviated_month: { $dateToString: {format: "%b", date: "$date", timezone: "+04:30" } },           full_month: { $dateToString: { format: "%B", date: "$date", timezone: "+04:30" } }        }      }    ] ) 
操作返回以下结果:
{    "_id" : 1,    "yearMonthDayUTC" : "2014-01-01",    "timewithOffsetNY" : "03:15:39:736-0500",    "timewithOffset430" : "12:45:39:736+0430",    "minutesOffsetNY" : "-300",    "minutesOffset430" : "270",    "abbreviated_month": "Jan",    "full_month": "January" }