Reputation: 4083
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);
Upvotes: 66
Views: 72295
Reputation: 4014
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 updateDefinition = new List<UpdateDefinition<BsonDocument>>();
foreach (var dataField in metaData.Fields)
{
updateDefinition.Add(Builders<BsonDocument>.Update.Set(dataField.Name, dataField.Value));
}
var combinedUpdate = Builders<BsonDocument>.Update.Combine(updateDefinition);
await GetCollectionForClient().UpdateOneAsync(filter, combinedUpdate);
Upvotes: 12
Reputation: 11
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));
Upvotes: 1
Reputation: 369
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;
}
Upvotes: 1
Reputation: 116548
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");
Upvotes: 44
Reputation: 2525
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.
Upvotes: 25
Reputation: 417
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 })
Upvotes: 2
Reputation: 97
var _personobj = _person
{
Id = 10, // Object ID
Email="[email protected]",
Phone=123456,
};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);
Upvotes: 4
Reputation: 53685
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");
Upvotes: 148