I want to update an auto increment field in MongoDB through Vapor and MongoKitten. Not necessarily a unique key.
The goal is to use $inc modifier in order to make it a single atomic operation and get the returned incremented result all in one go.
Is there support for this operation with MongoKitten?
Can I achieve this e.g. by using findAndUpdate method?
If yes what would be an example syntax of this?
With MongoKitten you can use the findAndUpdate
function on Collection to do this. The input should be a query (unless you want to increment all entities in the collection) and a with
argument for the update document.
// The query used to find the document to increment
let query: Query = "_id" == ...
Inside the update Document, you can use the $inc operator like so:
let updateDoc: Document = ["$inc": ["myKey": 1]]
This will update the "myKey" by incrementing it by 1
let updated = try collection.findAndUpdate(query, with: updateDoc)
The updated
document will contain the document before updating, so if myKey
has a value of 3. It'll be incremented to 4 after this query, but you'll receive the document with the value 3
.
To change this you can change the returnedDocument
argument (which defaults to .old
)
let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)
Finally, if you care about optimisation or just find limiting your returned results in general you should consider adding a projection. Projections indicate to the database which fields you are and are not interested in.
You can use it with the findAndUpdate
to ensure only the relevant field(s) are returned, which is the myKey
integer value in this example.
let updated = try collection.findAndUpdate(query, with: updateDoc, returnedDocument: .new)