【问题标题】:MongoDB C# Update only fields that are not nullMongoDB C#仅更新不为空的字段
【发布时间】:2016-08-12 12:41:52
【问题描述】:

我有一个文件,例如

{
    "_id": "ABC",
    "name": "Bob",
    "age": 42
}

我有 2 个函数在不同时间单独运行。函数 A 更新名称,函数 B 更新年龄。这两个函数都会调用一个外部休息服务,该服务会根据服务返回名称或年龄。

我有一个映射到 mongo 文档的类

public class Person {
    [BsonId]
    public string Id { get; set; }

    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("age")]
    public int Age { get; set; }
}

函数 A 将仅填充此类的 Id 和 Name 属性,而函数 B 将填充 Id 和 Age 属性。

如何通过仅从函数 B 传递 Person 对象来更新 mongo 文档,以便它保留函数 A 的现有值?

我知道你可以做到Builders<Person>.Update.Set(x => x.Age, <new_age>),但我希望我的代码更加动态,这样如果我添加另一个名为“电话”的字段,我就可以调用一个通用方法,该方法将只更新具有值的字段并且不为空。

【问题讨论】:

  • 您更新的非空字段是什么?您在这里提出了几个问题...
  • 我想部分更新一个文档,函数 B 将只设置 Id 和 Age,因此 Name 将为空。我想知道是否有一种方法可以在不知道名称的情况下更新文档(无需先从数据库中拉回)并且不使用 .Set 方法。因此,就好像您只发送整个对象时使用 InsertOneAsync 方法一样。
  • 由于 Id 是 BsonId,您可以在不知道名称的情况下进行更新。使用 upserts,如果你的模式是可变的,最好使用 BsonDocument 而不是强类型的 Person 对象。

标签: c# mongodb


【解决方案1】:

仅将要更新的元素添加到新的 BsonDocument 中,以便创建更新定义。

private static void SetUpdatableElements(BsonDocument bdoc, BsonDocument updateDefintion, HashSet<string>() excluded = null, string parentName = "")
{
    var excluded = excluded ?? new HashSet<string>()
    parentName = !string.IsNullOrWhiteSpace(parentName) ? $"{parentName}." : "";
    foreach (var item in bdoc)
    {
        if (item.Value.IsObjectId || // skip _id                     
            item.Value.IsBsonNull || // skip properties with null values
            excluded.Contains(item.Name)) // skip other properties that should not be updated
        {
            continue;
        }
        if (!item.Value.IsBsonDocument) // to avoid override nested objects)
        {
            updateDefintion = updateDefintion.Add($"{parentName}{item.Name}", item.Value);
            continue;
        }
        // recursively set nested elements to avoid overriding the full object
        SetUpdatableElements(item.Value.ToBsonDocument(), updateDefintion, item.Name);
    }
}

调用者:

var person = new Person() { Id = "ABC", Name = "bob", Age:42, Phone="123 456 7890"}
var updateDefintion = new BsonDocument();
var bDoc = person.ToBsonDocument();
SetUpdatableElements(person.ToBsonDocument(), updateDefintion, new HashSet<string>(nameof(person.Name)))
collection.UpdateOneAsync<Person>(p => p.Id == person.Id, new BsonDocument("$set", updateDefintion));

最后,你的 updateDefinition 应该是这样的:

{ {
    "$set": {
        "age": 42
        "phone": "123 456 7890"
    }
} }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2017-11-05
    • 2023-04-09
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多