Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$second
Amazon DocumentDB 中的$second运算符从日期或时间戳中提取秒部分。它用于从日期或时间戳字段中检索秒值。
参数
示例(MongoDB 外壳)
以下示例演示如何使用$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 }
]
代码示例
要查看使用该$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 ()