python - Atomically determine the "next" number in a MongoDB collection and assign it to a new document -
let's have mongodb collection of following layout:
{'number':1, '_id':...} {'number':2, '_id':...} {'number':4, '_id':...}
and on. demonstrated, not numbers present have consecutive.
i want write code (a) determines highest value number
found in collection , (b) inserts new document value number
1 higher current largest.
so if code operates on collection, no particular value number
should duplicated. issue that, done naively, creates race condition 2 threads of code running in parallel might find same highest value , insert same next highest number twice.
so how atomically? i'm working in python, prefer solution in language, accept answer explains concept in way can adapted language.
mongoengine you're looking in sequencefield.
create new collection called indexes
. collection this:
[ { '_id': 'mydata.number', 'next': 5 } ]
whenever you'd , set next index, use following statement:
counter = collection.find_and_modify( query = { '_id': 'mydata.number' }, update = { '$inc': { 'next': 1 } }, new = true, upsert = true)
what finds , updates sequence atomically in mongodb , retrieves next number. if sequence doesn't exist, generated.
thus, whenever want insert new value collection, call code above. if want maintain multple indexes across different collections , fields, modify mydata.number
string referencing "index."
Comments
Post a Comment