本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$tsIncrement
8.0.1 版中的新增内容。
Amazon DocumentDB 中的$tsIncrement运算符将时间戳值的递增序数作为长整数返回。
参数
示例(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()