Quick Start: C# and MongoDB - Update Operations

Ken W. Alger

#C#/.NET
C Sharp Quick Start

In the last edition of this C# Quick Start for MongoDB CRUD operations, we explored some of the different ways to Read data. We saw how to add filters to our query and how to sort the data. This post is about the Update operation and how the C# driver's Update and MongoDB work together to accomplish this important task.

Recall that we've been working with this BsonDocument version of a student record:

var document = new BsonDocument
            {
                { "student_id", 10000 },
                { "scores", new BsonArray
                    {
                    new BsonDocument{ {"type", "exam"}, {"score", 88.12334193287023 } },
                    new BsonDocument{ {"type", "quiz"}, {"score", 74.92381029342834 } },
                    new BsonDocument{ {"type", "homework"}, {"score", 89.97929384290324 } },
                    new BsonDocument{ {"type", "homework"}, {"score", 82.12931030513218 } }
                    }
                },
                { "class_id", 480}
            };

After getting part way through the grading term, our sample student's instructor notices that he's been attending the wrong class section. Due to this error the school administration has to change, or update, the class_id associated with his record. He'll be moving into section 483.

Updating Data

To update a document we need two bits to pass into an Update command. We need a filter to determine which documents will be updated. Second, we need what we're wanting to update.

Update Filter

For our example, we want to filter based on the document with student_id equaling 10000.

var filter = Builders<BsonDocument>.Filter.Eq("student_id", 10000)

Data to be Changed

Next, we want to make the change to the class_id. We can do that with Set() on the Update() method.

var update = Builders<BsonDocument>.Update.Set("class_id", 483);

Then we use the UpdateOne() method to make the changes. Note here that MongoDB will update at most one document using the UpdateOne() method. If no documents match the filter, no documents will be updated.

collection.UpdateOne(filter, update);

Array Changes

Not all changes are as simple as changing a single field. Let's use a different filter, one that selects a document with a particular score type for quizzes:

var arrayFilter = Builders<BsonDocument>.Filter.Eq("student_id", 10000) 
     & Builders<BsonDocument>.Filter.Eq("scores.type", "quiz");

Now if we want to make the change to the quiz score we can do that with Set() too, but to identify which particular element should be changed is a little different. We can use the positional $ operator to access the quiz score in the array. The $ operator on its own says "change the array element that we matched within the query" - the filter matches with scores.type equal to quiz and that element will get updated with the set.

var arrayUpdate = Builders<BsonDocument>.Update.Set("scores.$.score", 84.92381029342834);

And again we use the UpdateOne() method to make the changes.

collection.UpdateOne(arrayFilter , arrayUpdate);

Additional Update Methods

If you've been reading along in this blog series I've mentioned that the C# driver supports both sync and async interactions with MongoDB. Performing data Updates is no different. There is also an UpdateOneAsync() method available. Additionally, for those cases in which multiple documents need to be updated at once, there are UpdateMany() or UpdateManyAsync() options. The UpdateMany() and UpdateManyAsync() methods match the documents in the Filter and will update all documents that match the filter requirements.

Wrap Up

Update is an important operator in the CRUD world. Not being able to update things as they change would make programming incredibly difficult. Fortunately, C# and MongoDB continue to work well together to make the operations possible and easy to use. Whether it's updating a student's grade or updating a user's address, Update is here to handle the changes. The code for the Create, Read, and Update operations can be found in this gist.

We're winding down this C# Quick Start CRUD operation series with only one operation left to explore, Delete. In the next post, I'll show how to do that operation before we move onto the high power operations in MongoDB.

Get started with an M0 cluster on MongoDB Atlas today. It's free forever and you'll be able to work alongside this blog series.

Other articles in this Quick Start C# and MongoDB series:


Get Started with MongoDB Atlas

Run MongoDB in the cloud for free with MongoDB Atlas. No credit card required.