通过外键加入2个集合后的MongoDB全文搜索

时间:2018-07-03 09:02:14

标签: mongodb mongodb-query mongodb-java

我有一个名为Team的收藏。样本文档如下所示-

{ 
"_id" : "TEA000000006", 
"name" : "Team 1rrr", 
"teamMembers" : [
    {
        "_id" : "1", 
        "employeeRef" : "000000", 
        "teamRoleRef" : "TMR000000012"
    }, 
    {
        "_id" : "2", 
        "employeeRef" : "27375", 
        "teamRoleRef" : "TMR000000012"
    }, 
    {
        "_id" : "3", 
        "employeeRef" : "15607", 
        "teamRoleRef" : "TMR000000012"
    }, 
    {
        "_id" : "4", 
        "employeeRef" : "52321", 
        "teamRoleRef" : "TMR000000012"
    }, 
    {
        "_id" : "5", 
        "employeeRef" : "000000", 
        "teamRoleRef" : "TMR000000016"
    }, 
    {
        "_id" : "6", 
        "employeeRef" : "27375", 
        "teamRoleRef" : "TMR000000016"
    }, 
    {
        "_id" : "7", 
        "employeeRef" : "15607", 
        "teamRoleRef" : "TMR000000035"
    }, 
    {
        "_id" : "8", 
        "employeeRef" : "52321", 
        "teamRoleRef" : "TMR000000035"
    }
]
}

我还有一个收藏集-TeamMember。像这样的文档-

{
"_id" : "1",
"teamId" : "TEA000000006",
"employeeRef" : "000000",
"memberDisplayName" : "Anonoymous",
"memberTitle" : "BPO",
"memberLocation" : "Earth, Milkyway, Universe",
"memberBusinessPhone" : "123456789",
"memberEmail" : "anon@anon",
"teamRoleRef" : "TMR000000012",
"teamRoleSequence" : "4",
"roleName" : "Analyst"
}

在搜索Team时,我需要通过键TeamMemberTeam集合加入到teamRoleRef中。

我该如何做以及在MongoDB v3.4和Java MongoDB驱动程序(v2.0.6.RELEASE)中对此进行编码

1 个答案:

答案 0 :(得分:1)

db.Team.aggregate([
                {"$unwind" : "$teamMembers"},
                {"$project" : {"teamRoleRef" : "$teamMembers.teamRoleRef"}},
                {"$lookup" : {
                    "from" : "TeamMember",
                    "localField" : "teamRoleRef",
                    "foreignField" : "teamRoleRef",
                    "as" : "teamMember_docs"
                }}])

$lookup

Java驱动程序 Refer this link