[英]How does the $inc modifier work with concurrent requests in mongodb?
[英]MongoKitten support for $inc modifier
我想通過Vapor和MongoKitten更新MongoDB中的自動增量字段。 不一定是唯一鍵。
目的是使用$ inc修飾符,使其成為單個原子操作,並一次性獲得返回的遞增結果。
MongoKitten是否支持此操作?
我可以通過使用findAndUpdate方法來實現嗎?
如果是,這的示例語法是什么?
使用MongoKitten,您可以使用Collection上的findAndUpdate
函數來執行此操作。 輸入應該是一個查詢(除非您想增加集合中的所有實體)和一個用於更新文檔的with
參數。
// The query used to find the document to increment
let query: Query = "_id" == ...
在更新文檔中,您可以使用$ inc運算符,如下所示:
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)
最后,如果您關心優化或只是發現限制返回的結果,通常應該考慮添加一個投影。 投影向數據庫指示您對哪些字段感興趣,而對哪些字段不感興趣。
您可以將其與findAndUpdate
一起使用,以確保僅返回相關字段,在此示例中,該字段為myKey
整數值。
let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.