Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$hour
运$hour算符从日期或时间戳字段中提取小时部分。
参数
也可以按以下格式将参数指定为文档:
{日期:<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()