I need some persistence integer Id for an operation called about 100 times a second. I have a single document in Settings collection where id is stored in lastId field.
As per mongodb doc I want to implement it using findAnyModify() operation with update: { $inc: { lastId: 1 } } parameter. Can I rely on that each next call returns a new (incremented) number?
Or is it better as a workaround to use java AtomicLong counter? It will read lastId from mongo on start, and on each increment I will write (but not read) from mongo?
If you need a persisted sequence in mongodb, you indeed need to use the operator $inc in order to increment atomically on server side a given field that you will use as counter.
If you use an AtomicLong, you will hardly be able to guarantee the consistency of your sequence (especially in cluster environment) such that you could face situations where you end up with the same id for several documents.