$second (日期表达式)

适用对象: MongoDB vCore

运算符 $second 从日期值中提取秒部分,返回介于 0 和 59 之间的数字。 此运算符适用于需要二级粒度的精确时间戳分析和时间敏感作。

语法

$second 运算符的语法如下:

{
  $second: <dateExpression>
}

参数

DESCRIPTION
dateExpression 解析为 Date、Timestamp 或 ObjectId 的表达式。 如果表达式解析为 null 或缺失, $secondnull返回 。

示例:

让我们了解数据集中示例 JSON 的 stores 用法。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "location": { "lat": -48.9752, "lon": -141.6816 },
  "staff": { "employeeCount": { "fullTime": 12, "partTime": 19 } },
  "sales": {
    "salesByCategory": [ { "categoryName": "Desk Lamps", "totalSales": 37978 } ],
    "revenue": 37978
  },
  "company": "Trey Research",
  "city": "Lake Freeda",
  "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"),
  "lastUpdated": Timestamp({ "t": 1729983325, "i": 1 })
}

示例 1:从商店开张日期提取秒

本示例从商店开张日期中提取秒部分,以便进行精确的计时分析。

db.stores.aggregate([
  { $match: {"_id": "905d1939-e03a-413e-a9c4-221f74055aac"} },
  {
    $project: {
      name: 1,
      storeOpeningDate: 1,
      openingSecond: {
        $second: "$storeOpeningDate"
      }
    }
  }
])

查询从存储打开时间戳返回秒部分(25)。

{
  "_id": "905d1939-e03a-413e-a9c4-221f74055aac",
  "name": "Trey Research | Home Office Depot - Lake Freeda",
  "storeOpeningDate": ISODate("2024-09-26T22:55:25.779Z"),
  "openingSecond": 25
}