c# - 通过 C# MongoDB 驱动程序聚合查询结果
问题描述
MongoDB 数据库中有两个集合。Department
根据以下示例调用一个集合:
{
"_id": "Dept1",
"Description": "Department 1",
"ApplicationName": "Payroll",
"Version": 1
}
{
"_id": "Dept2",
"Description": "Department 2",
"ApplicationName": "Payroll",
"Version": 1
}
{
"_id": "Dept3",
"Description": "Department 3",
"ApplicationName": "Payroll",
"Version": 1
}
调用另一个集合UserAssociation
,其数据类似于以下示例:
{
"_id": "Associate1",
"DepartmentIds": ["Dept1","Dept2"]
}
{
"_id": "Associate2",
"DepartmentIds": ["Dept2","Dept3"]
}
{
"_id": "Associate3",
"DepartmentIds": ["Dept1", "Dept2","Dept3"]
}
这两个文档的 C# 模型是:
public class Department
{
public string Id { get; set; }
public string Description { get; set; }
public string ApplicationName { get; set; }
public int Version { get; set; }
}
public class Associate
{
public string Id { get; set; }
public string[] DepartmentIds { get; set; }
}
我想在一天结束时通过聚合或“加入” (任何可以帮助更好的东西)填充以下模型:
public class DepartmentAssociation
{
public string AssociateId { get; set; }
public Department[] Departments { get; set; }
}
如何在 C# 中实现这个目标?
解决方案
您需要将数据聚合到单个文档中,理想情况下这应该在存储点,但是如果您不能这样做,mongo 确实包含查找功能
它的语法是
$lookup:
{
from: "<collection to join>",
localField: "<field from the input documents>",
foreignField: "<field from the documents of the 'from' collection>",
as: "<output array field>"
}
或者如果你用 c# 编写它
PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
{
new BsonDocument("$lookup", new BsonDocument(){
{"from", "<collection to join>"},
{"localField", "<field from the input documents>"},
{"foreignField", "<field from the documents of the 'from' collection>"},
{"as", "<output array field>"}
}
};
using (var cursor = await collection.AggregateAsync(pipeline, options))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (BsonDocument document in batch)
{
Console.WriteLine(document.ToJson());
}
}
}
更具体的细节
PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
{
new BsonDocument("$lookup", new BsonDocument(){
{"from", "Department"},
{"localField", "DepartmentIds"},
{"foreignField", "_id"},
{"as", "Departments"}
}
};
using (var cursor = await collection.AggregateAsync<DepartmentAssociation>(pipeline, options))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (DepartmentAssociation document in batch)
{
...
}
}
}
推荐阅读
- laravel-5 - 如何在 API 身份验证中只允许不记名令牌?
- powerbi - 通过发布应用程序向用户授予权限时,如果数据集位于另一个工作区中,则它不适用于数据集
- database - Gremlin:提供的遍历器未映射到值
- angular - Angular 11 错误:您在预期流的位置提供了无效对象。您可以提供 Observable、Promise、Array 或 Iterable
- android-location - 如何以编程方式匹配android中的两个位置?
- python - python discord bot-只是无法在线(只是一个简单的问题)
- php - 使用 PHP 的 X & Y 标记表
- javascript - 如何连接两个输入?
- postgresql - 在 pg_restore 期间以自定义格式 (-F c) 备份 PostgreSQL 失败(日志中的复制命令)
- node.js - 提高流视频帧性能的方法