0

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)

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for reply. From the code, is it means the Project() method with Projection.Include() tells MongoDB driver to return only the fields specified?
Yes, correct. You can see more examples here: mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/…
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.