Can find and insert multiple documents be done in a transaction without creating duplicates?

Hello,

I want to build some feature that initializes data for a “company” when a component/endpoint is accessed the first time without the risk of getting duplicates if 2 users or more access that endpoint at the same time.

I have something like this, pseudocode

list = items.find(companyId)
if(list.length === 0){
  defaultList = items.find({default: true});
  defaultList.map(di=>{
    //set new company id, remove default flag
    delete di._id
  })
  items.insertMany(defaultList)
  list = items.find(companyId)
}
return list

I hope that if I wrap everything in a transaction(multi-document transaction maybe) and use a session for all queries, I can avoid duplicates when 2 or more users access the endpoint simultaneously.

Any examples out there to look at, thoughts on the validity of this approach?

Thank you

Hello @Stefan_Badea ,

Welcome to The MongoDB Community Forums! :wave:

As per this blog on ACID Properties in MongoDB

MongoDB supports multi-document ACID transactions for the use cases that require them. Developers appreciate the flexibility of being able to model their data in a way that does not typically require multi-document transactions but having multi-document transaction capabilities available in the event they do.

This means that the Isolation property ensures that all transactions run in an isolated environment. That enables running transactions concurrently because transactions don’t interfere with each other.

Now If multi document transactions try to update same document simultaneously, then only the transaction which acquired the lock first for that particular document will be executed and others will get TransientTransactionError. Another case is, if companyId is indexed and multiple transactions are trying to add same value for companyId simultaneously, then the first one to commit will be kept and others will get MongoServerError: E11000 duplicate key error. However I would recommend you to test this behaviour with your specific use case, to ensure that the application can handle different failure scenarios.

To learn more about Multi-document transactions, please go through below links

Regards,
Tarun