c# - 如何使用 Mongodb C# 驱动程序加入多个集合
问题描述
我需要将 3 个集合与多个$lookup
我在 C# 驱动程序中尝试过的集合合并,它允许我进行$lookup
用户集合,但不能$lookup
为设置集合执行第二个集合。
任何人都可以帮忙吗?
db.Transactions.aggregate([
{
$lookup:
{
from: "Account",
localField: "AccountId",
foreignField: "_id",
as: "Account"
}
},
{
$lookup:
{
from: "User",
localField: "UserId",
foreignField: "_id",
as: "User"
}
}
])
.match({
})
.project({})
这是 C# 代码:
var account = _dbClient.GetDatabase(_dbName).GetCollection<Account>("Accounts");
var user = _dbClient.GetDatabase(_dbName).GetCollection<User>("Users");
var transaction = _dbClient.GetDatabase(_dbName).GetCollection<Transaction>("Transactions");
var result = (from t in transaction.AsQueryable()
join a in account.AsQueryable() on t.AccountId equals a.Id
join u in user.AsQueryable() on t.UserId equals u.Id into userList
from acc in userList.DefaultIfEmpty()
where acc.CompanyName.ToLower().Contains(companyName) && c.CreatedDate >= fromDate && c.CreatedDate <= toDate
select new TransactionHistory
{
Id = t.Id,
CompanyName = acc.CompanyName,
UserId = u.UserId
FirstName = u.FirstName
}).ToList();
我在$project or $group does not support {document}.
使用 Linq 时遇到了错误。
解决方案
我需要使用多个 $lookup 将 3 个集合加入聚合中
给定以下类:
public class Transactions
{
public ObjectId Id { get; set; }
public int UserId { get; set; }
public int AccountId { get; set; }
public int SettingId { get; set; }
}
public class Account
{
public int Id {get; set;}
public int Name {get; set;}
}
public class User
{
public int Id {get; set;}
public int Name {get; set;}
}
public class Setting
{
public int Id {get; set;}
public int Name {get; set;}
}
您可以使用MongoDB .NET/C# 驱动程序(当前为 v2.9)执行多个$lookup阶段,如下所示:
var collection = database.GetCollection<Transactions>("transactions");
var docs = collection.Aggregate()
.Lookup("account", "AccountId", "_id", "asAccounts")
.Lookup("user", "UserId", "_id", "asUsers")
.Lookup("setting", "SettingId", "_id", "asSettings")
.As<BsonDocument>()
.ToList();
foreach (var doc in docs) {
Console.WriteLine(doc.ToJson());
}
如果您想过滤特定值,可以在中间/之前/之后添加Match 。请记住,每个Lookup
阶段后更改后的文件。
值得一提的是,如果您需要加入多个集合作为您的常见操作的一部分,您应该重新考虑数据库数据模型。请参阅架构设计:摘要了解更多信息。
推荐阅读
- javascript - 动态填充复选框并在反应 redux 中维护复选框的状态
- javascript - 主机和选项之间缺少分隔斜线
- ocaml - 将 OCaml Bigarray.Array1 的切片复制到字节
- css - 你如何在角度(css表)的表格单元格中将文本对齐=左文本居中?
- f# - F# printf 填充
- python - numpy数组索引错误问题
- python - Windows PermissionError & tempfile 模块
- java - 什么 web 框架支持 Ctrl+Shift+G 进入表示层?
- angular - Angular 7,如何处理对 asp.net web api 的多个调用
- excel - 如何改进这个类模块定义