

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# \$1second
<a name="second"></a>

Amazon DocumentDB 中的`$second`运算符从日期或时间戳中提取秒部分。它用于从日期或时间戳字段中检索秒值。

**参数**
+ `expression`：要从中提取秒值的日期或时间戳字段。此表达式可以是字段路径，也可以是任何解析为日期或时间戳的有效表达式。

## 示例（MongoDB 外壳）
<a name="second-examples"></a>

以下示例演示如何使用`$second`运算符从日期字段中提取秒分量。

**创建示例文档**

```
db.users.insertMany([
  { name: "John", dob: new Date("1990-05-15T12:30:45Z") },
  { name: "Jane", dob: new Date("1985-09-20T23:59:59Z") },
  { name: "Bob", dob: new Date("2000-01-01T00:00:00Z") }
]);
```

**查询示例**

```
db.users.aggregate([{ $project: { name: 1, dobSeconds: { $second: "$dob" } } }])
```

**输出**

```
[
  { "_id" : ObjectId("6089a9c306a829d1f8b456a1"), "name" : "John", "dobSeconds" : 45 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a2"), "name" : "Jane", "dobSeconds" : 59 },
  { "_id" : ObjectId("6089a9c306a829d1f8b456a3"), "name" : "Bob", "dobSeconds" : 0 }
]
```

## 代码示例
<a name="second-code"></a>

要查看使用该`$second`命令的代码示例，请选择要使用的语言的选项卡：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const users = db.collection('users');

  const result = await users.aggregate([{ $project: { name: 1, dobSeconds: { $second: '$dob' } } }]).toArray();
  console.log(result);

  await client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    users = db['users']

    result = list(users.aggregate([{'$project': {'name': 1, 'dobSeconds': {'$second': '$dob'}}}]))
    print(result)

    client.close()

example ()
```

------