$hour - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

$hour

$hour 연산자는 날짜 또는 타임스탬프 필드에서 시간 구성 요소를 추출합니다.

파라미터

  • dateExpression: 연산자가 적용되는 날짜입니다. 이는 유효한 BSON 날짜(예: $createdAt 또는 날짜 리터럴과 같은 필드)로 확인되어야 합니다.

파라미터는 다음 형식의 문서로 지정할 수도 있습니다.

{ 날짜: <dateExpression>, 시간대: <timezoneExpression> }

이렇게 하면가 시간대 인식 날짜 작업을 적용할 수 있습니다.

- `<tzExpression>`: (optional) The timezone of the operation result. It must be a valid expression that resolves to a string formatted as either an Olson Timezone Identifier or a UTC Offset. If no timezone is provided, the result is in UTC.

예제(MongoDB 쉘)

다음 예제에서는 $hour 연산자를 사용하여 날짜 필드에서 시간 구성 요소를 추출하고 그에 따라 데이터를 그룹화하는 방법을 보여줍니다.

샘플 문서 생성

db.events.insertMany([ { timestamp: new Date("2023-04-01T10:30:00Z") }, { timestamp: new Date("2023-04-01T12:45:00Z") }, { timestamp: new Date("2023-04-02T08:15:00Z") }, { timestamp: new Date("2023-04-02T16:20:00Z") }, { timestamp: new Date("2023-04-03T23:59:00Z") } ]);

쿼리 예제

db.events.aggregate([ { $project: { hour: { $hour: "$timestamp" } } }, { $group: { _id: "$hour", count: { $sum: 1 } } }, { $sort: { _id: 1 } } ]);

출력

[ { "_id": 8, "count": 1 }, { "_id": 10, "count": 1 }, { "_id": 12, "count": 1 }, { "_id": 16, "count": 1 }, { "_id": 23, "count": 1 } ]

이 쿼리는 timestamp 필드의 시간 구성 요소를 기준으로 이벤트를 그룹화하고 각 시간에 대한 이벤트 수를 계산합니다.

코드 예제

$hour 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('events'); const result = await collection.aggregate([ { $project: { hour: { $hour: "$timestamp" } } }, { $group: { _id: "$hour", count: { $sum: 1 } } }, { $sort: { _id: 1 } } ]).toArray(); console.log(result); } catch (error) { console.error('Error occurred:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from datetime import datetime def example(): try: 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": { "hour": {"$hour": "$timestamp"} } }, { "$group": { "_id": "$hour", "count": {"$sum": 1} } }, { "$sort": {"_id": 1} } ])) print(result) except Exception as e: print(f"An error occurred: {e}") finally: client.close() example()