.NET - MongoDb从文档中删除子文档

问题描述 投票:0回答:1

我有一个包含以下数据的集合

{
  "_id": "4e3951905e746b3805000000",
  "Name": "John",
  "Surname": "Mayer",
  "Comments": [
    {
      "_id": "4e3951965e746b8007000001",
      "content": "a"
    }
  ]
}

例如,我想del id一个id为4e3951965e746b8007000001的子文档所以这个子文档应该被删除

这是我的csharp代码

public static void UpdateContentById(string id)
 {
    var defination = Builders<Client>.Update.PullFilter(p => p.Comments, c => c.Id == "4e3951965e746b8007000001");

    db.UpdateOne(p => p.Id == id, defination);
 }

这是我期待的结果。

{
   "_id": "4e3951905e746b3805000000",
   "Name": "John",
   "Surname": "Mayer"
}
c# mongodb mongodb-query
1个回答
1
投票

从数组中删除最后一个元素时,数组字段本身不会被删除。通常这是一种理想的行为。如果您有这样的模型:

public class Client
{
    public ObjectId Id { get; set; }

    public List<Comment> Comments { get; set; }
}

Comments字段将被反序列化为空列表。与数据库文档中缺少Comments字段的情况不同,在这种情况下,Comments属性将保留为null。这将需要在应用程序逻辑中对null进行额外检查,否则可能导致NullReferenceException。除非在构造对象时初始化列表:

public List<Comment> Comments { get; set; } = new List<Comment>();

现在Comments将被设置为空列表,即使文档中缺少该属性。然而,这与文档中的Comments数组刚刚留空完全相同。

所以我没有看到删除空数组字段的意义。但是,如果由于某种原因需要此行为,则应在元素拉取后自行执行另一个更新:

db.UpdateOne(p => p.Id == id, defination);
db.UpdateOne(p => p.Id == id && !p.Comments.Any(), Builders<Client>.Update.Unset(p => p.Comments));
© www.soinside.com 2019 - 2024. All rights reserved.