使用子数组在两个集合之间进行连接

时间:2018-11-27 03:08:27

标签: c# mongodb

我在Mongodb中是新手,很难设计数据库。基本上我有2个收藏集,分别是 useraccount domainorganisation 。以下是每个集合的文档示例:

域组织:

{
    "_id" : ObjectId("5bf95046a1bc1b47c4fe75f2"),
    "IsActive" : true,
    "Participators" : [ 
        {
            "_id" : ObjectId("5bf95044a1bc1b47c4fe75ef"), // useraccountid
            "Role" : "Loader",
            "AssignedBy" : "CONSOLE"
        }
    ]
}

用户帐户:

{
    "_id" : ObjectId("5bf95044a1bc1b47c4fe75ef"),
    "Username" : "test-1",
    "Email" : "myemail1@email.com",
    "IsSystemAdministrator" : false,
    "UserProfile" : {
        "FirstName" : "firsttest1",
        "LastName" : "lasttest1"
    }
}

我想按如下方式加入这两个收藏集:

{
    "_id" : ObjectId("5bf95046a1bc1b47c4fe75f2"),
    "IsActive" : true,
    "Participators" : [ 
        {
            "Acc" : {
                "_id" : ObjectId("5bf95044a1bc1b47c4fe75ef"),
                "Username" : "test-1",
                "Email" : "myemail1@email.com",
                "IsSystemAdministrator" : false,
                "UserProfile" : {
                        "FirstName" : "firsttest1",
                        "LastName" : "lasttest1"
                        }
        }
            "Role" : "Loader",
            "AssignedBy" : "CONSOLE"
        }
    ]
}

我当前的解决方案是通过查询两个集合并完全匹配数据来处理应用程序逻辑中的联接。但是只是想知道我是否可以在mongodb层中解决这个问题。

1 个答案:

答案 0 :(得分:1)

您可以像这样建立查询。

    db.getCollection('domainorganisation').aggregate([
    {
        "$unwind": "$Participators"
    },
    {
        "$lookup":
        {
            "from": "useraccount",
            "localField": "Participators._id",
            "foreignField": "_id",
            "as": "Joined"
        }
    },
    {
        "$group": {
            "_id": "$_id",
            "Participators": {
                "$push": {
                    "Acc": { "$arrayElemAt": ["$Joined", 0] },
                    "Role": "$Participators.Role",
                    "AssignedBy": "$Participators.AssignedBy"
                }
            },
            "IsActive": { "$first": "$IsActive" }
        }
    }
])