Search code examples
c#mongodbmongodb-.net-driver

How to retrieve nested array element from MongoDB using C#


Now I have one entity and a nested array

public class Author {
    public ObjectId Id { get; set; }
    public String Name { get; set; }
    public IEnumerable<Book> Books { get; set; }
}

public class Book {
    public ObjectId Id { get; set; }
    public String ISBN { get; set; }
}

and pre defined mongodb collections like

var authors = mongodbDatabase.getCollection<Author>("Authors");

Here's the problem, is there a way to directly retrieve one or some "Book" from MongoDB with specified "Author" (not to retrieve the entire "Author" then LINQ the books I want)


Solution

  • You can use Projection as follows:

    var filter = Builders<Author>.Filter.Eq("Books.ISBN", "987654321");
    var projection = Builders<Author>.Projection.Include("Books.$").Exclude("_id");
    var book = context.AuthorCollection.Find(filter).Project(projection).SingleOrDefault();
    

    This will return a BsonDocument which has the book.