requirements:
similar message queues multiple users fetch numbers from a table at the same time to ensure that each user gets different numbers and then immediately add user_id
db.foo.findOneAndUpdate({"user_id":{$exists:false}, {$set:{user_id:"123456"}},{sort:{_id:1}}})
official documentation does not specify whether the command is thread safe
if there is a record as follows
{"_id":1}
{"_id":2}
{"_id":3}
Is it possible for 5 users to request at the same time to get a record with _ id
as 1?
developed a script using Python to verify that it seems thread-safe but not sure that the application code is explicitly locked just to be on the safe side. The Python code is as follows:
def query_and_set_user_id(user_id):
result = db.test.find_one_and_update({"user_id":{"$exists":False}},{"$set": {"user_id": user_id}}, sort=[("id", 1)])
print(threading.current_thread(), result)
return result
max_workers = 5
pool = ThreadPoolExecutor(max_workers)
futures = []
for i in range(max_workers):
f = pool.submit(query_and_set_user_id, "user_{}".format(i+1))
futures.append(f)
wait(futures)