View a markdown version of this page

$tsSecond - Amazon DocumentDB

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

$tsSecond

8.0.1 版中的新增内容。

Amazon DocumentDB 中的$tsSecond运算符将时间戳值的秒部分作为长整数(Unix 纪元秒)返回。

参数

  • expression:解析为时间戳的表达式。

示例(MongoDB Shell)

以下示例说明如何使用$tsSecond运算符从时间戳值中提取秒数部分。

创建示例文档

db.events.insertMany([ {_id: 1, ts: Timestamp(1678900000, 1)}, {_id: 2, ts: Timestamp(1678900000, 2)}, {_id: 3, ts: Timestamp(1678900001, 1)} ]);

查询示例

db.events.aggregate([ { $project: { seconds: { $tsSecond: "$ts" } } } ]);

输出

[ {_id: 1, seconds: Long("1678900000")}, {_id: 2, seconds: Long("1678900000")}, {_id: 3, seconds: Long("1678900001")} ]

代码示例

要查看使用$tsSecond运算符的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient, Timestamp } = require('mongodb'); async function example() { const client = new MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); try { await client.connect(); const db = client.db('test'); const collection = db.collection('events'); const result = await collection.aggregate([ { $project: { seconds: { $tsSecond: "$ts" } } } ]).toArray(); console.log(result); } finally { 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') try: db = client['test'] collection = db['events'] result = list(collection.aggregate([ {'$project': {'seconds': {'$tsSecond': '$ts'}}} ])) print(result) finally: client.close() example()