3

At work I'm contributing to an application that will be used many people and processes. MongoDb is used for storing data. We foresee that there will be concurrency issues if we don't get the update actions right. Since I'm rather new to MongoDb, I'm doing a proof of concept at home. Inserting and deleting works fine, but then there are the updates.

Consider the following record of a movie:

{
  "ID": "74733528-a491-4a73-8462-eca00f63c400",
  "Title": "The Matrikx",
  "Year": "1979",
  "Duration": "3h16min",
  "Categories": [
    {
     "Category": "Action"
    },
    {
     "Category": "Sci-Fi"
    }
   ],
  "Reviews": [
   {
     "ReviewerId": "82c53033-e6dd-4745-89e4-74ab29ff17be",
     "ReviewerName": "Keanu",
     "Comment": "The best movie ever"
   },
   {
    "ReviewerId": "49c906a4-4f42-41b4-9a30-fee764fa04a1",
    "ReviewerName": "Laurence",
    "Comment": "The best movie ever++"
   }
 ]
}

I foresee a scenario in which two users, User1 and User2, simultaneously fetch this document from Mongo and subsequently edit the same document. Say User1 corrects the Title and the Year. User2 did not change these fields, but updates the Duration field and the comment posted by Laurence. Both users should be able to persist their changes without overwriting the changes made by the other user.

Using C# and MongoDb Driver v2.2, how can I update only a few properties dynamically instead of replacing the whole document? I've seen several answers on SO prescribing e.g.

Builders<BsonDocument>.Update.Set("key1","value1").Set("key2","value2")

but I don't see how this can be useful unless I know during coding what fields will be set. The accepted answer to this SO question proposes to use Update.Combine, which seems better. What is the practical approach for getting the keys (e.g. Title and Year for User1)? For User2, who also modified the second review, I need to build the key to "Reviews.$.1.Title". The fact that I need to determine which field has been updated and also which element of the collection was modified, makes life difficult. Can anyone either sketch how they have solved such a problem, or point me to a tutorial addressing these issues?

1

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.