适用对象:
MongoDB vCore
运算符 $tsSecond
从时间戳返回秒值。 时间戳由两个部分组成:时间值(自纪元以来的秒数)和递增值。 此运算符提取秒部分,表示 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的时间。
语法
$tsSecond
运算符的语法如下:
{
$tsSecond: <expression>
}
参数
DESCRIPTION | |
---|---|
expression |
计算结果为时间戳的表达式。 如果表达式的计算结果不为时间戳, $tsSecond 则返回错误。 |
示例:
让我们了解数据集中示例 JSON 的 stores
用法。
{
"_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 }),
"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,
lastUpdatedSeconds: {
$tsSecond: "$lastUpdated"
},
lastUpdatedDate: {
$toDate: {
$multiply: [
{ $tsSecond: "$lastUpdated" },
1000
]
}
}
}
}
])
这将生成一个输出,其中显示了时间戳及其相应日期中的秒值:
{
"_id": "2cf3f885-9962-4b67-a172-aa9039e9ae2f",
"name": "First Up Consultants | Bed and Bath Center - South Amir",
"lastUpdatedSeconds": Long("1640995200"),
"lastUpdatedDate": ISODate("2022-01-01T00:00:00.000Z")
}