Is there a way in mongodb to add a new document, setting one of the field values based on other documents in the collection, atomically?

In SQL this would be expressed similar to

DECLARE @nextNumber INT = (SELECT MAX(number) + 1 FROM MyTable WITH UPDLOCK)

INSERT INTO MyTable(name, number) VALUES ('My Name', @nextNumber)


I cant find any examples of this kind of thing in MongoDB that would not be a two step, non atomic operation. Is this even going to be possible with MongoDb?

Hi @Andrew_Stanton ,

If you need to read the number as a snapshot isolation you should consider using transactions the same way you used in the sql example.

Otherwise you may consider using a $merge command where you fetch the max number , increase it by one and merge results into a new collection.


can you link an example of one or both of those?