Projection of mongodb subdocument using C# .NET driver 2.0

As Avish said, you have to use the aggregation API to get the resulting document to look like you are wanting. However, the driver can make some of that disappear for you if you use the expression tree API for project as you have done for Find. For instance, I believe the following should work for you:

var taskNames = await Categores.Find(x => x.CategoryName == catName)
    .Project(x => x.Tasks.Select(y => y.Name))
    .ToListAsync();

This should just bring back an enumerable of strings (tasks.name) for each category. The driver will be inspecting this projection and only pull back the tasks.name field.


MongoDB doesn't really support projections the way SQL databases do; you can ask for a partial document, but you'd still get back something that matches the schema of the document you were querying. In your case, you're getting back only the tasks field, and for each task, only the name field.

You can easily transform this into a list of strings using plain LINQ:

var categoryTasks = Categories.Find<Category>(x => x.CategoryName == catName)
                     .Project(Builders<Category>.Projection
                                                .Include("tasks.name")
                                                .Exclude("_id"))
                     .ToListAsync()
                     .Result;   

var taskNames = categoryTasks.Tasks.Select(task => task.Name).ToList();

Alternatively, you can do some fancy stuff with the aggregations API (which does support custom projections, kinda), but that would probably be overkill for you case.