首页 > 解决方案 > 如何使用 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 时遇到了错误。

标签: c#mongodbmongodb-csharp-2.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;}
}

您可以使用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阶段后更改后的文件。

值得一提的是,如果您需要加入多个集合作为您的常见操作的一部分,您应该重新考虑数据库数据模型。请参阅架构设计:摘要了解更多信息。


推荐阅读