以下代码将允许我更新FirstName =“john”和LastName =“Doe”的电子邮件。如何在不使用Save()方法的情况下更新电子邮件和电话?
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);
答案 0 :(得分:80)
这很简单;),只需在您的更新中添加另一组或其他操作:
var update = Update.Set("Email", "jdoe@gmail.com")
.Set("Phone", "4455512");
答案 1 :(得分:26)
您还可以使用通用和类型安全的Update<TDocument>
:
var update = Update<Person>.
Set(p => p.Email, "jdoe@gmail.com").
Set(p => p.Phone, "4455512");
答案 2 :(得分:5)
我想更新N个字段,这是我如何实现的
我使用了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);
答案 3 :(得分:3)
var _personobj = _person
{
Id = 10, // Object ID
Email="jdoe@gmail.com",
Phone=123456,
};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);
答案 4 :(得分:2)
对于条件更新,您可以使用类似
return ' '.join([s for s in procLine.split(' ') if len(s) > 2])
或者只是弹出记录,然后修改并替换它。
答案 5 :(得分:1)
如果您想再一次更新文档字段,请选择多标记。
例如mongodb 2.0或3.0v:
yourCollection.Update(_filter
, _update
, new MongoUpdateOptions() { Flags = UpdateFlags.Multi })