$year - Amazon DocumentDB

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

$year

Amazon DocumentDB 中的$year运算符从日期或时间戳中提取年份部分。

参数

  • expression:要从中提取年份部分的日期或时间戳表达式。

示例(MongoDB 外壳)

以下示例演示如何使用$year运算符从日期字段中提取年份部分。

创建示例文档

db.events.insertMany([ { "_id": 1, "date": ISODate("2023-04-15T00:00:00Z") }, { "_id": 3, "date": ISODate("2021-12-31T00:00:00Z") } ]);

查询示例

db.events.aggregate([ { $project: { year: { $year: "$date" } } } ]);

输出

[ { "_id": 1, "year": 2023 }, { "_id": 3, "year": 2021 } ]

代码示例

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

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: { year: { $year: "$date" } } } ]).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': {'year': {'$year': '$date'}}} ])) print(result) client.close() example()