运算符 $hour
将日期的小时部分作为介于 0 和 23 之间的数字返回。 运算符接受解析为 Date、Timestamp 或 ObjectId 的日期表达式。
语法
{
$hour: <dateExpression>
}
参数
参数 | DESCRIPTION |
---|---|
dateExpression |
解析为 Date、Timestamp 或 ObjectId 的表达式。 如果表达式解析为 null 或缺失, $hour 则返回 null。 |
示例:
让我们了解 stores
数据集中的示例 json 的用法。
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"name": "Relecloud | Toy Collection - North Jaylan",
"location": {
"lat": 2.0797,
"lon": -94.4134
},
"staff": {
"employeeCount": {
"fullTime": 7,
"partTime": 4
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "Educational Toys",
"totalSales": 3299
}
],
"revenue": 3299
},
"promotionEvents": [
{
"eventName": "Massive Markdown Mania",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 29
}
},
"discounts": [
{
"categoryName": "Remote Control Toys",
"discountPercentage": 6
},
{
"categoryName": "Building Sets",
"discountPercentage": 21
}
]
}
],
"company": "Relecloud",
"city": "North Jaylan",
"lastUpdated": {
"$timestamp": {
"t": 1733313006,
"i": 1
}
},
"storeOpeningDate": "2024-09-05T11:50:06.549Z"
}
示例 1:从当前日期提取小时
该示例演示如何从当前日期和时间中提取 hour
数据。
db.stores.aggregate([
{ $match: { "_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a" } },
{
$project: {
name: 1,
storeOpeningDate: 1,
currentHour: { $hour: new Date() },
documentHour: { $hour: "$storeOpeningDate" }
}
}
])
该查询从 ObjectId 创建时间返回当前小时和小时。
{
"_id": "e6410bb3-843d-4fa6-8c70-7472925f6d0a",
"name": "Relecloud | Toy Collection - North Jaylan",
"storeOpeningDate": "2024-09-05T11:50:06.549Z",
"currentHour": 12,
"documentHour": 11
}
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。