簡體   English   中英

如何在C#Mongodb強類型驅動程序中刪除嵌套文檔數組內的元素

[英]How to delete an element inside array of a nested document in C# Mongodb strongly typed 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

您需要獲取存儲的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是集合實例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM