Search code examples
c#mongodbtransactionspushinsertion

How to perform "all or nothing" operation with mongoDB?


I need insert some elements in a field array on a document. Well... I know that Mongo has atomic Update.Push... The fact is that I need to do this insertion in many documents. The case is that following (I need insert a roles array for every username):

 public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string role in roleNames)
            {
                if (!this.RoleExists(role))
                {
                    throw new ProviderException(String.Format("The role '{0}' was not found.", role));
                }
            }

            //How to guarantee that all users will be updated with roles?
            foreach (string user in usernames)
            {
                var docs = this.users.Update(Query.And(Query.EQ("Username", user),
                    Query.EQ("Applications.Name", this.ApplicationName)), Update.AddToSetEach("Applications.$.Roles", 
                   new BsonArray(roleNames)));
            }
        }

Suppose the connection down at moment of "pushing" of roles to third username. I need rollback the previous operations. Any idea?


Solution

  • From what I understand about MongoDB, it is not ACID compliant with regards to multiple collections. Now, if you are updating a single collection at a time, you should be good. Otherwise, non-ACID compliance is part of the warning label on the box, if you will.