View a markdown version of this page

$tsIncrement - Amazon DocumentDB

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

$tsIncrement

8.0.1 版的新功能。

Amazon DocumentDB 中的$tsIncrement運算子會從時間戳記值傳回增量序數,做為長整數。

參數

  • expression:解析為時間戳記的表達式。

範例 (MongoDB Shell)

下列範例顯示如何使用 $tsIncrement運算子從時間戳記值中擷取序數增量。

建立範例文件

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: { increment: { $tsIncrement: "$ts" } } } ]);

輸出

[ {_id: 1, increment: Long("1")}, {_id: 2, increment: Long("2")}, {_id: 3, increment: Long("1")} ]

程式碼範例

若要檢視使用 $tsIncrement 運算子的程式碼範例,請選擇您要使用的語言標籤:

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: { increment: { $tsIncrement: "$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': {'increment': {'$tsIncrement': '$ts'}}} ])) print(result) finally: client.close() example()