c# - 带有 POCO 类的 mongodb graphLookup c# 示例
问题描述
有没有机会使用带有 POCO 类而不是 bson 文档的 graphLookup 聚合阶段?我发现的所有示例都使用 BsonDocuments,这让我非常困惑。谢谢。
解决方案
让我们以想要获取库中给定类别的面包屑结果的示例场景为例......
这是一个完整的程序,它插入一些种子数据并使用 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();
}
}
}
推荐阅读
- rxjs - rxjs 中 scan(...) 和 subscribe(...) 的区别
- android - 证书颁发机构不受信任,在 android webview 中但在移动浏览器中工作正常
- android - 如何使用 GoogleMap SDK 列出附近的地点?
- algorithm - 确定分治算法的适当递归函数
- python - 如何用两个 2D 数组 (x,y) 和 0D 数组即标量 (z) 绘制等高线图?
- scala - 如何从 parquet 文件中选择 13 位时间戳列,将其转换为日期并存储为数据框?
- reactjs - 如何修复'动作必须是普通对象。使用自定义中间件进行异步操作。
- c - 格式化打印指针值
- ansible-awx - 如何向 AWX docker 添加回调插件
- c# - 在循环中突然停止的特定路径中创建 (N) 个目录