适用对象:
MongoDB vCore
运算符 $tsIncrement
从时间戳返回递增值。 MongoDB 中的时间戳由两个部分组成:时间值(自纪元以来的秒数)和递增值。 此运算符提取增量部分。
语法
$tsIncrement
运算符的语法如下:
{
$tsIncrement: <expression>
}
参数
DESCRIPTION | |
---|---|
expression |
计算结果为时间戳的表达式。 如果表达式的计算结果不为时间戳, $tsIncrement 则返回错误。 |
示例:
让我们了解数据集中示例 JSON 的 stores
用法。 出于演示目的,我们将添加时间戳字段以显示工作原理 $tsIncrement
。
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"location": {
"lat": 60.7954,
"lon": -142.0012
},
"staff": {
"totalStaff": {
"fullTime": 18,
"partTime": 17
}
},
"sales": {
"totalSales": 37701,
"salesByCategory": [
{
"categoryName": "Mattress Toppers",
"totalSales": 37701
}
]
},
"lastUpdated": Timestamp({ t: 1640995200, i: 5 }),
"storeOpeningDate": ISODate("2021-10-03T00:00:00.000Z"),
"promotionEvents": [
{
"eventName": "Price Drop Palooza",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 9,
"Day": 21
},
"endDate": {
"Year": 2024,
"Month": 9,
"Day": 30
}
},
"discounts": [
{
"categoryName": "Bath Accessories",
"discountPercentage": 18
},
{
"categoryName": "Pillow Top Mattresses",
"discountPercentage": 17
},
{
"categoryName": "Bathroom Scales",
"discountPercentage": 9
}
]
}
]
}
示例 1:从审核时间戳中提取增量
从审核日志中上次更新的时间戳中提取增量值。
db.stores.aggregate([
{ $match: {"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f"} },
{
$project: {
name: 1,
lastUpdatedIncrement: {
$tsIncrement: "$auditLog.lastUpdated"
}
}
}
])
这将生成一个输出,其中显示了时间戳中的增量值:
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"lastUpdatedIncrement": Long("5")
}