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

下列範例示範如何使用 $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()