BH4EHN
BH4EHN

Reputation: 169

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)

Upvotes: 0

Views: 3869

Answers (2)

Okan SARICA
Okan SARICA

Reputation: 327

A different way without any static string

var filter = Builders<Author>.Filter.ElemMatch(p=>p.Books,t=>t.ISBN == "987654321");
var projection = Builders<Author>.Projection.Include(p=>p.Books[-1]);
var author = context.AuthorCollection.Find(filter).Project<Author>(projection).SingleOrDefault();

Please note that the data you need will return as an author and you can reach it from author.Books

Upvotes: 2

Mahdi
Mahdi

Reputation: 3349

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.

Upvotes: 2

Related Questions