首页 > 解决方案 > 带有 POCO 类的 mongodb graphLookup c# 示例

问题描述

有没有机会使用带有 POCO 类而不是 bson 文档的 graphLookup 聚合阶段?我发现的所有示例都使用 BsonDocuments,这让我非常困惑。谢谢。

标签: c#mongodbgraphlookup

解决方案


让我们以想要获取库中给定类别的面包屑结果的示例场景为例......

这是一个完整的程序,它插入一些种子数据并使用 graphlookup 聚合阶段来获取Mindfulness类别的面包屑:

注意:为了简洁起见,我使用MongoDB.Entities了库。对于官方驱动程序,聚合查询将是相同的。

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();
        }
    }
}

推荐阅读