Is there any chance to use graphLookup aggregate stage with POCO classes and not bson documents? All examples I've found are using BsonDocuments and it makes me really confused. Thanks.
            Asked
            
        
        
            Active
            
        
            Viewed 1,198 times
        
    1 Answers
2
            let's take the example scenario of wanting to get back a breadcrumb result for a given category in a library...
here's a full program that inserts some seed data and uses a graphlookup aggregation stage to get the breadcrumb for the Mindfulness category:
note: i've used MongoDB.Entities library for brevity. the aggregate query would be the same for the official driver.
using MongoDB.Driver;
using MongoDB.Entities;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TestApplication
{
    public class Category : Entity
    {
        public string Name { get; set; }
        public string ParentCategory { get; set; }
    }
    public class Result
    {
        public string[] BreadCrumb { get; set; }
    }
    public static class Program
    {
        private static async Task Main()
        {
            await DB.InitAsync("test");
            await new[] {
                new Category { Name = "Books" },
                new Category { Name = "Sci-Fi", ParentCategory = "Books" },
                new Category { Name = "Space", ParentCategory = "Sci-Fi" },
                new Category { Name = "AI", ParentCategory = "Sci-Fi" },
                new Category { Name = "Self-Help", ParentCategory = "Books" },
                new Category { Name = "Mindfulness", ParentCategory = "Self-Help" },
                new Category { Name = "Hypnotherapy", ParentCategory = "Self-Help" }
            }.SaveAsync();
            var collection = DB.Collection<Category>();
            var result = await collection.Aggregate()
                .Match(c => c.Name == "Mindfulness")
                .GraphLookup<Category, string, string, string, Category, IEnumerable<Category>, object>(
                    from: collection,
                    connectFromField: nameof(Category.ParentCategory),
                    connectToField: nameof(Category.Name),
                    startWith: $"${nameof(Category.Name)}",
                    @as: "BreadCrumb",
                    depthField: "order")
                .Unwind("BreadCrumb")
                .SortByDescending(x => x["BreadCrumb.order"])
                .Group("{_id:null, BreadCrumb:{$push:'$BreadCrumb'}}")
                .Project("{_id:0, BreadCrumb:'$BreadCrumb.Name'}")
                .As<Result>()
                .ToListAsync();
            var output = string.Join(" > ", result[0].BreadCrumb);
            Console.WriteLine(output); //Books > Self-Help > Mindfulness
            Console.ReadLine();
        }
    }
}
        Dĵ ΝιΓΞΗΛψΚ
        
- 5,068
 - 3
 - 13
 - 26