MongoKitten支持$ inc修饰符

问题描述 投票:0回答:1

我想通过Vapor和MongoKitten更新MongoDB中的自动增量字段。不一定是唯一的钥匙。

目标是使用$ inc修饰符以使其成为单个原子操作并一次性获得返回的递增结果。

MongoKitten是否支持此操作?

我可以实现这个目标吗通过使用findAndUpdate方法?

如果是,这将是一个示例语法?

mongodb vapor mongokitten
1个回答
0
投票

使用MongoKitten,您可以使用Collection上的findAndUpdate函数来执行此操作。输入应该是查询(除非您要增加集合中的所有实体)和更新文档的with参数。

// The query used to find the document to increment
let query: Query = "_id" == ...

在更新文档中,您可以像这样使用$inc operator

let updateDoc: Document = ["$inc": ["myKey": 1]]

这将通过将“myKey”递增1来更新它

let updated = try collection.findAndUpdate(query, with: updateDoc)

updated文档将在更新之前包含文档,因此如果myKey的值为3.在此查询之后它将增加到4,但您将收到值为3的文档。

要更改此设置,您可以更改returnedDocument参数(默认为.old

let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)

最后,如果您关心优化或只是发现限制返回的结果,您应该考虑添加投影。 Projections向数据库指出您对哪些字段感兴趣,哪些字段不感兴趣。

您可以将它与findAndUpdate一起使用以确保仅返回相关字段,这是此示例中的myKey整数值。

let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)
© www.soinside.com 2019 - 2024. All rights reserved.