从嵌套数组聚合,查找和addField

时间:2018-11-03 11:18:14

标签: mongodb mongodb-query

我在使用MongoDB查询时遇到麻烦。 首先,我有一个“ testScriptResultCollection ”,其结构如下:

{
    testCaseId: x
    testScriptId: 1
    descripttion: aaa

}
{
    _id: 2
    testCaseId: x
    testScriptId: 2
    descripttion: bbb
}
{
    _id: 3
    testCaseId: x
    testScriptId: 3
    descripttion: ccc
}

,另一个集合是“ testCaseCollection”

{
    _id: 1
    testCaseId: x
    testScripts: [
        {
            testScriptId: 1
            name: testScript1_Name
        },
        {
            testScriptId: 2
            name: testScript2_Name
        }
        {
            testScriptId: 3
            name: testScript3_Name
        }
    ]
}

我需要提取一个对象,例如:

 [ 
        {
            testCaseId: x
            testScriptId: 1
            descripttion: aaa
            name: testScript1_Name
        },
        {
            testCaseId: x
            testScriptId: 2
            descripttion: bbb
            name: testScript2_Name
        },
        {
            testCaseId: x
            testScriptId: 3
            descripttion: ccc
            name: testScript3_Name
        },
    ]

我曾尝试通过查询查询使用“ testCaseId” 的两个集合,并找到testScriptId的“名称” ,但这样做出错了

testScriptResultCollection.aggregate{[
    {
        $match: {testCaseId : x}
    },
    {
            $lookup:
            {
                from: "testCaseCollection"
                localField: "testCaseId",
                foreignField: "testCaseId",
                as: "combineResults"
            }
    },
    {
        $addFields : 
        {
            "name": {
                $filter: { 
                    input: "$combineResults.testScripts",
                    as: "testScriptArr",
                    cond: { $eq: ["$$testScriptArr.testScriptId", $testScriptId]}
                }
            }
        }
    }
]}

有人可以帮我吗。任何帮助,将不胜感激。非常感谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下汇总

基本上,您需要使用$mergeObjects合并两个集合对象,最后使用$replaceRoot将它们移到顶层。

db.getCollection('testCaseCollection').aggregate([
  { "$unwind": "$testScripts" },
  { "$lookup": {
    "from": "testScriptResultCollection",
    "localField": "testScripts.testScriptId",
    "foreignField": "testScriptId",
    "as": "newField"
  }},
  { "$unwind": "$newField" },
  { "$replaceRoot": { "newRoot": { "$mergeObjects": ["$newField", "$testScripts"] }}}
])