53

以下代码将允许我更新 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);
4

7 回答 7

129

这很简单;),只需在您的更新中添加另一组或其他操作:

 var update = Update.Set("Email", "jdoe@gmail.com")
                    .Set("Phone", "4455512");
于 2011-01-27T19:43:47.480 回答
36

您还可以使用泛型和类型安全Update<TDocument>

var update = Update<Person>.
    Set(p => p.Email, "jdoe@gmail.com").
    Set(p => p.Phone, "4455512");
于 2014-07-12T13:16:00.120 回答
15

对于条件更新,您可以使用类似

        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 });

或者直接弹出记录,然后修改替换。

于 2018-09-23T00:59:21.853 回答
9

我想更新多个 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);
于 2020-04-25T20:13:40.210 回答
3
var _personobj = _person
{
    Id = 10, // Object ID
    Email="jdoe@gmail.com",
    Phone=123456,

};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);
于 2015-11-07T14:22:29.467 回答
2

如果您想再更新一个文档的字段,请选择多标志。

例如 mongodb 2.0 或 3.0v:

yourCollection.Update(_filter
                      , _update
                      , new MongoUpdateOptions() { Flags = UpdateFlags.Multi })  
于 2017-04-21T10:21:45.627 回答
1

您需要单独设置每个属性。因此,对于具有多个字段的对象,此扩展非常方便:

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;
    }

并被称为:

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;
    }
于 2021-12-29T08:04:24.690 回答