Search code examples
c#mongodb-.net-driver

Exclude items from a collection inside a document with mongodb c# driver


I have an application written in C# that uses the c# driver for mongoDB. The delete is logical, so the entities have a Boolean property deleted. So imagine that I have these classes:

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; }
}

and I want to get all the not deleted Authors with their not deleted books, but I'm not sure how to exclude the books from the result.

I have this piece of code, but I cannot exclude the deleted books.

_collection.FindAsync(x => !x.Deleted)).ToList();

What am I missing?


Solution

  • You could exclude deleted books by adding projection with inner filter:

    _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();
    

    It could happen that all books for the author are deleted. If you want to filter such authors with no active books from the result output, add appropriate check:

    _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();