Designing a mongodb sub-box using C # .NET driver 2.0

I have the following structure:

public class Category { [BsonElement("name")] public string CategoryName { get; set; } [BsonDateTimeOptions] [BsonElement("dateCreated")] public DateTime DateStamp { get; set; } [BsonElement("tasks")] public List<TaskTracker.Task> Task { get; set; } } public class Task { [BsonElement("name")] public string TaskName { get; set; } [BsonElement("body")] public string TaskBody { get; set; } } 

I am trying to query Category to get all TaskName values ​​and then return them to the list that will be displayed in the list.

I tried using this query:

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

But what comes back: {"tasks": [{"name: "test"}]} .

Is it possible to simply return the value of a string?

+8
source share
3 answers

As Aviss said, you need to use the aggregation API to get the resulting document the way you want. However, the driver may make some of them disappear for you if you use the expression tree APIs for the project, as was done for Find. For example, 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 simply return an enumerated string ( tasks.name ) for each category. The driver checks this projection and discards only the tasks.name field.

+17
source

MongoDB does not support predictions like SQL databases do; you can request a partial document, but you will still return something that matches the outline of the document you requested. In your case, you are returned only in the tasks field, and for each task - only the name field.

You can easily convert this to a list of strings using a simple 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 aggregation API (which supports custom forecasts, curious ones), but this will probably be redundant for you.

+4
source

@Craig Wilson

I have a similar question, but I want to select the whole task, not just the name.

0
source

Source: https://habr.com/ru/post/985433/


All Articles