View a markdown version of this page

$date ToParts - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$date ToParts

5.0.1 和 8.0 版本的新增内容

Amazon DocumentDB 中的$dateToParts聚合运算符返回的文档包含日期和时间值的组成部分,例如年、月、日、时、分、秒和毫秒。

参数

  • date:要分成部分的日期和时间值。

  • timezone:(可选)提取日期部分时要使用的时区。如果未指定,则以 UTC 格式返回零件。

  • iso8601:(可选)如果设置为true,则返回的文档将使用 ISO 8601 日期部分(isoWeekYearisoWeekisoDayOfWeek)。默认值为 false

示例(MongoDB 外壳)

以下示例演示如何使用$dateToParts运算符返回日期的各个部分。

创建示例文档

db.events.insertMany([ { _id: 1, eventDate: ISODate("2023-04-01T10:30:15Z") }, { _id: 2, eventDate: ISODate("2023-12-25T18:45:00Z") } ]);

查询示例

db.events.aggregate([ { $project: { _id: 1, parts: { $dateToParts: { date: "$eventDate" } } } } ])

输出

[ { "_id": 1, "parts": { "year": 2023, "month": 4, "day": 1, "hour": 10, "minute": 30, "second": 15, "millisecond": 0 } }, { "_id": 2, "parts": { "year": 2023, "month": 12, "day": 25, "hour": 18, "minute": 45, "second": 0, "millisecond": 0 } } ]

代码示例

要查看使用该$dateToParts命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const collection = db.collection('events'); const result = await collection.aggregate([ { $project: { _id: 1, parts: { $dateToParts: { date: "$eventDate" } } } } ]).toArray(); console.log(result); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['events'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'parts': { '$dateToParts': { 'date': '$eventDate' } } } } ])) print(result) client.close() example()