1

I have a question, and its about how mongo will handle if 2 user at same time make a update request to update the data with the $set function like this

Update reuqest 1:

{
   $set: {
      'field1' : 'new data'
   }
}

Update request 2:

{
   $set: {
      'field2' : 'secound data'
   }
}

if i using mysql, its will update each field without eny issue, will mongodb do the same?

the next case can be i have 3 users and there will be a update like this

Update request 1:

{
   $set: {
      'field1' : 'data'
   }
}

Update request 2:

{
   $set: {
      'field1' : 'data',
      'field2' : 'data'
   }
}

Update request 3:

{
   $set: {
      'field2' : 'data'
   }
}

in this case if i do the same in MySQL its will request 2 overwirte the field1 from request 1 and the request 3 will overwirte the field2 data in request 2.

and i expect mongo work at the same way? or can i make a version control over a document so i can se changes over time?

i need to prevent this case, becures i'm building a huges API layer where evey thing use Mongo and i want to update product catalog on cross from platform to platform.

hope eny how can help me to understand this part in MongoDB

2 Answers 2

2

With (multiple) updates to (single) document, first come, first served. So, that client who is first (in time) get lock to that document, others who come later, will get "ticket" (queue number) and will wait their turn to update that document.

So, update 2 will override field1 value and add field2, update 3 then will override field2 value..

3
  • Okay so there wil no way to self control it or? :) Commented Jun 1, 2017 at 9:02
  • Mongo don't have transactions, so no concurrent updates possible --> last update wins.
    – JJussi
    Commented Jun 1, 2017 at 11:31
  • @JJussi mongo does have transactions, but thats for multiple documents. docs.mongodb.com/manual/core/transactions
    – Luk Aron
    Commented Dec 25, 2020 at 14:15
1

I believe your question has two aspects to it:

  • versioning
  • transactions

As at MongoDB 3.4 neither of these aspects have built-in server features, however both are possible to implement in application logic. The most suitable approach will depend on your requirements. Depending on the programming language you are using and the desired approach, there may even be helper libraries or implementations available.

For document versioning there is a great blog series on the Ask Asya blog which includes code examples and caveats:

Updates in MongoDB are atomic at the document level, so you can achieve transaction-like semantics if single-document atomicity is sufficient. For more complicated updates involving multi-document transactions you will need to consider a design pattern like two phase commits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.