如何在C#Mongodb强类型驱动程序中删除嵌套文档数组内的元素

时间:2018-04-12 06:16:37

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

我正在使用官方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

1 个答案:

答案 0 :(得分:4)

您需要存储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是集合实例