汇总,从2个集合中查找并提取结果

时间:2018-11-06 07:19:19

标签: mongodb mongodb-query aggregation-framework

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

[
    {
        _id: 1,
        testCaseId: 'x',
        testScriptId: 1,
        createById: 1
    },
    {
        _id: 2,
        testCaseId: 'x',
        testScriptId: 2,
        createById: 2
    }
]

,另一个集合是“ testCaseCollection”

[
    {
        _id: 1,
        testCaseId: x,
        testScripts: [
            {
                testScriptId: 1,
                testScriptName: 'testScript1_Name'
            },
            {
                testScriptId: 2,
                testScriptName: 'testScript2_Name'
            }
        ]
    }
]

最后一个集合是“ membersCollection”

[
    {
        _id: 1,
        userName: 'John'
    },
    {
        _id: 2,
        userName: 'Mark'
    }
]

我需要从“ testCaseCollection” (通过 testCaseId testScriptId 来提取在“ testScriptResultCollection”上查找每个记录的结果中提取其结果) testScriptName )和“ membersCollection” (由 userId 获得其 userName

我想要的结果如下:

 [ 
        {
            _id: 1,
            testCaseId: 'x',
            testScriptId: 1,
            createById: 1,
            testScriptName: 'testScript1_Name',
            userName: 'John'
        },
        {
            _id: 2,
            testCaseId: 'x',
            testScriptId: 2,
            createById: 2,
            testScriptName: 'testScript2_Name',
            userName: 'Mark'
        },
    ]

我已经尝试过下面的链接这样的查询,但这并不是最好的方法。 https://mongoplayground.net/p/dGdPGV3GEQn

安妮妮可以帮助我吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用以下优化的聚合管道

db.testScriptResultCollection.aggregate([
  { "$match": { "testCaseId": "x" }},
  { "$lookup": {
    "from": "testCaseCollection",
    "let": { "testScriptId": "$testScriptId" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$$testScriptId", "$testScripts.testScriptId"] }}},
      { "$unwind": "$testScripts" },
      { "$match": { "$expr": { "$eq": ["$$testScriptId", "$testScripts.testScriptId"] }}},
      { "$project": { "testScripts": 1, "_id": 0 }}
    ],
    "as": "tr"
  }},
  { "$lookup": {
    "from": "membersCollection",
    "let": { "createById": "$createById" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$$createById", "$_id"] }}}
    ],
    "as": "user"
  }},
  { "$addFields": {
    "testScriptName": { "$arrayElemAt": [ "$tr.testScripts.testScriptName", 0 ] },
    "userName": { "$arrayElemAt": ["$user.userName", 0] }
  }},
  { "$project": { 'user': 0, "tr": 0 }}
])