我有一个用C#编写的应用程序,它使用mongoDB的c#驱动程序。删除是合乎逻辑的,因此实体具有布尔属性已删除。所以想象我有这些课程:
public class Author
{
public string Id { get; set; }
public string Name { get; set; }
public IList<Book> Books { get; set; }
public bool Deleted { get; set; }
}
public class Book
{
public string Id { get; set; }
public string Name { get; set; }
public bool Deleted { get; set; }
}
我希望将所有未删除的作者与未删除的图书一起删除,但我不确定如何从结果中排除图书。
我有这段代码,但我无法排除已删除的图书。
_collection.FindAsync(x => !x.Deleted)).ToList();
我错过了什么?
答案 0 :(得分:1)
您可以通过添加带内置过滤器的投影来排除已删除的图书:
_collection.Find(x => !x.Deleted)
.Project(x => new Author
{
Id = x.Id,
Name = x.Name,
Books = x.Books.Where(b => !b.Deleted).ToList(),
Deleted = x.Deleted,
}) .ToList();
可能会删除作者的所有书籍。如果要从结果输出中过滤没有活动书籍的作者,请添加相应的检查:
_collection.Find(x => !x.Deleted && x.Books.Any(b => !b.Deleted))
.Project(x => new Author
{
Id = x.Id,
Name = x.Name,
Books = x.Books.Where(b => !b.Deleted).ToList(),
Deleted = x.Deleted,
}) .ToList();