Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); 
like image 694
atbebtg Avatar asked Jan 27 '11 16:01

atbebtg


People also ask

Is it possible to update MongoDB field using value of another field?

Starting from MongoDB 4.2 you can perform Updates with an Aggregation Pipeline. An aggregation pipeline enables more expressive updates including calculated fields and references to other field values in the same document.

How do I update an array in MongoDB?

You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.


1 Answers

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"); 
like image 93
Andrew Orsich Avatar answered Oct 09 '22 20:10

Andrew Orsich