View a markdown version of this page

$tsSecond - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$tsSecond

8.0.1 版的新功能。

Amazon DocumentDB 中的$tsSecond運算子會以長整數 (Unix epoch 秒) 傳回時間戳記值的秒部分。

參數

  • 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()