简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM