How do you update multiple field using Update.Set in MongoDB using official c# driver?
-
26-10-2019 - |
Question
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 = "john.doe@gmail.com";
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", "jdoe@gmail.com");
_person.Update(myQuery, update);
Solution
It's very simple ;), just add another set or some else operation to the your update:
var update = Update.Set("Email", "jdoe@gmail.com")
.Set("Phone", "4455512");
OTHER TIPS
You can also use the generic and type-safe Update<TDocument>
:
var update = Update<Person>.
Set(p => p.Email, "jdoe@gmail.com").
Set(p => p.Phone, "4455512");
var _personobj = _person
{
Id = 10, // Object ID
Email="jdoe@gmail.com",
Phone=123456,
};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);
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.
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 })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow