该 $dayOfMonth
运算符从日期值中提取月份的日期(1-31)。 它可用于根据月份日期对文档进行分组或筛选。
Syntax
{ $dayOfMonth: <dateExpression> }
参数
参数 | Description |
---|---|
<dateExpression> |
要从中提取月份日期的日期表达式。 |
例子
让我们了解 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:提取月份的日期
查询使用 $dayOfMonth
运算符从时间戳中提取月份(1-31)的 lastUpdated
日期。 它有助于隔离报告或分组的日期组件。
db.stores.aggregate([
{
$match: { _id: "e6410bb3-843d-4fa6-8c70-7472925f6d0a" }
},
{
$project: {
_id: 0,
dayOfMonth: { $dayOfMonth: "$lastUpdated" }
}
}
])
结果显示发生月份 lastUpdated
的数值日。 在当前方案中,4 作为日期为“2024-12-04”。
{
"dayOfMonth": "4"
}
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。