$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()