![](/img/trans.png)
[英]How to filter based on nested array element in C# Mongodb strongly typed driver
[英]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.