【问题标题】:How to delete an element inside array of a nested document in C# Mongodb strongly typed driver如何在 C# Mongodb 强类型驱动程序中删除嵌套文档数组中的元素
【发布时间】:2018-04-12 06:16:36
【问题描述】:

我正在使用官方的 C# MongoDb 强类型驱动程序 2.5.0 版本与 MongoDB 进行交互。

考虑以下类:

public class Author
{

    public Author()
    {

    }

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string BirthDate { get; set; }

    public string ScientificDegree { get; set; }

    public Library Library { get; set; }
}

public class Library
{
    public DateTime DateAdded { get; set; }

    public DateTime LastModified { get; set; }

    public List<Book> Books { get; set; }

    [BsonDefaultValue(0)]
    public int ReadCount { get; set; }

}

如何使用作者库中的 id 删除一本书?这是我直接从数组中删除元素的代码。

var field = new ExpressionFieldDefinition<Library, List<Book>>(library => library.Books);

var bookFilter = Builders<Book>.Filter.Eq(book => book.Id, bookId);

var update = Builders<Library>.Update.PullFilter(field, bookFilter);

//How to apply the update to the author using author id

【问题讨论】:

    标签: c# .net mongodb mongodb-query mongodb-.net-driver


    【解决方案1】:

    您需要获取存储的 Library 并对该 Library 对象执行更改并将其更新回文档。另一种方法是使用PullFilter 删除它

    var update = Builders<Author>.Update.PullFilter(x=>x.Library.Books,Builders<Book>.Filter.Eq(x=>x.id,bookId));
    db.Author.UpdateOneAsync(x => x.Id.Equals(autherId), update).Result;
    

    db.Author 是集合实例

    【讨论】:

    • 这个方案不方便,我想直接在一个操作中找到并更新Library对象,除非MongoDB不支持这个功能。
    • 引用问题中的数组是文档中的直接元素,在我的情况下与数组是嵌套文档的元素不一样,谢谢回复。
    • 感谢您的回答
    • 如何更新数组元素的属性?
    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2022-11-28
    • 2021-02-26
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多