我需要将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();
我使用Linq收到错误$project or $group does not support {document}.
。
答案 0 :(得分:0)
我需要通过多个$ 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;}
}
您可以使用$lookup(当前为v2.9)执行以下多个MongoDB .NET/C# driver阶段:
var collection = database.GetCollection(“ 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
阶段之后都对文档进行了修改。
值得一提的是,如果您需要在常见操作中加入多个集合,则应重新考虑database data model。有关更多信息,请参见Schema Design: Summary。