How do you update multiple field using Update.Set in MongoDB using official c# driver?

C#.NetMongodbMongodb .Net-Driver

C# Problem Overview


The following code will allow me to update the Email where FirstName = "john" and LastName = "Doe". How do you update both Email and Phone without using Save() method?

MongoDB.Driver.MongoServer _server = MongoDB.Driver.MongoServer.Create("mongodb://localhost");
MongoDB.Driver.MongoDatabase _dataBase = _server.GetDatabase("test");
MongoDB.Driver.MongoCollection<Person> _person = _dataBase.GetCollection<Person>("person");

//Creat new person and insert it into collection
ObjectId newId  = ObjectId.GenerateNewId();
Person newPerson = new Person();
newPerson.Id = newId.ToString();
newPerson.FirstName = "John";
newPerson.LastName = "Doe";
newPerson.Email = "[email protected]";
newPerson.Phone = "8005551222";
_person.Insert(newPerson);

//Update phone and email for all record with firstname john and lastname doe
MongoDB.Driver.Builders.QueryComplete myQuery = MongoDB.Driver.Builders.Query.And(MongoDB.Driver.Builders.Query.EQ("FirstName", "John"),    MongoDB.Driver.Builders.Query.EQ("LastName", "Doe"));
MongoDB.Driver.Builders.UpdateBuilder update = MongoDB.Driver.Builders.Update.Set("Email", "[email protected]");

_person.Update(myQuery, update);

C# Solutions


Solution 1 - C#

It's very simple ;), just add another set or some else operation to the your update:

 var update = Update.Set("Email", "[email protected]")
                    .Set("Phone", "4455512");

Solution 2 - C#

You can also use the generic and type-safe Update<TDocument>:

var update = Update<Person>.
    Set(p => p.Email, "[email protected]").
    Set(p => p.Phone, "4455512");

Solution 3 - C#

For conditional updating you can use something like

        var updList = new List<UpdateDefinition<MongoLogEntry>>();
        var collection = db.GetCollection<MongoLogEntry>(HistoryLogCollectionName);

        var upd = Builders<MongoLogEntry>.Update.Set(r => r.Status, status)
            .Set(r => r.DateModified, DateTime.Now);
        updList.Add(upd);

        if (errorDescription != null)
            updList.Add(Builders<MongoLogEntry>.Update.Set(r => r.ErrorDescription, errorDescription));

        var finalUpd = Builders<MongoLogEntry>.Update.Combine(updList);

        collection.UpdateOne(r => r.CadNum == cadNum, finalUpd, new UpdateOptions { IsUpsert = true });

Or just pop out the record, then modify and replace it.

Solution 4 - C#

I wanted to update multiple N number of fields here's how I achieved it

I used Builders<T>.Update.Combine

// Get the id for which data should be updated
var filter = Builders<BsonDocument>.Filter.Eq("_id", ObjectId.Parse(_id));

// Add Data which we wants to update to the List
var updateDefination = new List<UpdateDefinition<BsonDocument>>();
foreach (var dataField in metaData.Fields)
{
	updateDefination.Add(Builders<BsonDocument>.Update.Set(dataField.Name, dataField.Value));
}
var combinedUpdate = Builders<BsonDocument>.Update.Combine(updateDefination);
await GetCollectionForClient().UpdateOneAsync(filter, combinedUpdate);

Solution 5 - C#

var _personobj = _person
{
    Id = 10, // Object ID
    Email="[email protected]",
    Phone=123456,
    
};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);

Solution 6 - C#

if you want to one more update document's field then pick multi flag.

> for example mongodb 2.0 or 3.0v:

yourCollection.Update(_filter
                      , _update
                      , new MongoUpdateOptions() { Flags = UpdateFlags.Multi })  

Solution 7 - C#

You need to Set each property individually. So for an object with multiple fields this extension can be handy:

public static UpdateDefinition<T> ApplyMultiFields<T>(this UpdateDefinitionBuilder<T> builder, T obj)
    {
        var properties = obj.GetType().GetProperties();
        UpdateDefinition<T> definition = null;

        foreach (var property in properties)
        {
            if (definition == null)
            {
                definition = builder.Set(property.Name, property.GetValue(obj));
            }
            else
            {
                definition = definition.Set(property.Name, property.GetValue(obj));
            }
        }

        return definition;
    }

And be called like this:

public async Task<bool> Update(StaffAccount model)
    {
        var filter = Builders<StaffAccount>.Filter.Eq(d => d.Email, model.Email);

        // var update = Builders<StaffAccount>.Update.Set(d => d, model); // this doesnt work
        var update = Builders<StaffAccount>.Update.ApplyMultiFields(model);

        var result = await this.GetCollection().UpdateOneAsync(filter, update);

        return result.ModifiedCount > 0;
    }

Solution 8 - C#

We can pass variables as tuple.

    public async Task Update(string id, params (Expression<Func<TEntity, dynamic>> field, dynamic value)[] list)
    {
        var builder = Builders<TEntity>.Filter;
        var filter = builder.Eq("_id", id);

        var updateBuilder = Builders<TEntity>.Update;
        var updates = new List<UpdateDefinition<TEntity>>();
        foreach (var item in list)
            updates.Add(updateBuilder.Set(item.field, item.value));

        var result = await _dbCollection.UpdateOneAsync(filter, updateBuilder.Combine(updates));
    }

Usage:

await _userRepository.Update(user.id, (x => x.bio, "test"), (x => x.isEmailVerified, false));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatbebtgView Question on Stackoverflow
Solution 1 - C#Andrew OrsichView Answer on Stackoverflow
Solution 2 - C#i3arnonView Answer on Stackoverflow
Solution 3 - C#Liam KernighanView Answer on Stackoverflow
Solution 4 - C#Mihir DaveView Answer on Stackoverflow
Solution 5 - C#KathirView Answer on Stackoverflow
Solution 6 - C#Biletbak.comView Answer on Stackoverflow
Solution 7 - C#user1912383View Answer on Stackoverflow
Solution 8 - C#Utku GenelView Answer on Stackoverflow