如何在 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
是集合实例
我正在使用官方 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
是集合实例