【问题标题】:Set subproperty on potentially null property in MongoDB in C#在 C# 中的 MongoDB 中为可能为空的属性设置子属性
【发布时间】:2016-10-14 15:59:47
【问题描述】:

对于 MongoDB,使用 C# 驱动程序,我需要为属性 x 构造一个更新

  • x.y 设置为42
  • 如果x 为空,则有效
  • 如果x 已设置为具有其他属性的对象(在这种情况下,我需要保留这些属性),这也有效。

换句话说,我需要为属性x 构建一个更新,将x.y 设置为42,并同时作用于以下两个输入文档:

{
  "x": null
}

should become

{
  "x": {
    "y": 42
  }
}

{
  "x": {
    "z": 66
  }
}

should become

{
  "x": {
    "y": 42,
    "z": 66
  }
}

天真的做法

Builders<BsonDocument>.Update.Set("x.y", 42)

导致错误信息

cannot use the part (x of x.y) to traverse the element ({x: null})

【问题讨论】:

    标签: c# mongodb


    【解决方案1】:

    这里的理想解决方案是清理数据以使该字段不为空。您可以在模型中的属性上使用 [BsonIgnoreIfNull] 来帮助阻止首先设置 null。

    但要实现此目的,您需要执行 2 次操作

    首先检查x是否为null,如果不是,则对“x”执行更新(AddToSet),如果是则执行更新以设置整个“x”(Set)

    这个没有测试,但是例如:

    var fb = Builders<YourObject>.Filter;
    
    var idFilter = fb.Eq(f => f.Id, "");//Your filter otherwise you will be updating all documents
    var nullFilter = fb.Eq(f => f.x, BsonNull.Value);//Filter to check x is set to null
    
    var result = await Collection.Find(fb.And(idFilter, nullFilter))
    .CountAsync()
    .ConfigureAwait(false);
    
    var toAppend = new BsonDocument("y", 42);
    
    if (result > 0)
    {
        var update = Builders<YourObject>.Update.AddToSet(f => f.x, toAppend);
    
        await Collection.UpdateOneAsync(f => idFilter, update).ConfigureAwait(false);
    }
    else
    {
        var update = Builders<YourObject>.Update.Set(f => f.x, toAppend);
    
        await Collection.UpdateOneAsync(x => idFilter, update).ConfigureAwait(false);
    }
    

    这是另一个暗示同样事情的问题:

    Update with AddToSet not updating null value with MongoDB C#

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 1970-01-01
      相关资源
      最近更新 更多