Is mongodb findOneAndUpdate thread safe?

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)
Mar.30,2021

is thread safe.
actually findAndModify behaves the same as update , and the two functions are not interrupted between queries and updates. The difference is that findAndModify can also return pre-updated or updated documents after the operation. More differences can be found in the document Comparisons with the update Method


Application locking cannot solve the problem of distributed deployment of programs.

this is a bit like out-of-queue in a queue. If A can get a message, the message cannot be accessed by B. If mongo is used for this kind of concurrency control, I am generally purple:

    The
  1. record adds a processing status field, such as processStatus . The default value is 0 unprocessed 1 processing 2 processing success 3 processing failure 4 retry.
  2. takes advantage of the atomic nature of findAndModify.
  the principled and transactional nature of mongo  

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e53b7e-66bf7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e53b7e-66bf7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?