0

Assuming I have a collection persons that has

[
    {
        id: 1,
        name: 'bob'
    },
    {
        id: 2,
        name: 'john'
    }
]

I want to have this function that updates both but if one fails the other also fails for example

function update() {
    db.persons.update({id: 1}, {$set: {name: 'alex'}});
    db.persons.update({id: 2}, {$set: {name: 'michael'}});
}

when I invoke update() there is a possibility that one will success and the other will fail. The behavior that I want is that either both succeed or both fail (without changing the database)

Community
  • 1
  • 1
Ahmed Soliman
  • 365
  • 1
  • 4
  • 12

1 Answers1

0

you could do something like this

function update() {
    if ((db.persons.find({id:1 })).nMatched!=0 && (db.persons.find({id:2 })).nMatched!=0){
        db.persons.update({id: 1}, {$set: {name: 'alex'}});
        db.persons.update({id: 2}, {$set: {name: 'michael'}}); 
    }else{
        //do nothing
    }
}
vivek jha
  • 344
  • 1
  • 11