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