【问题标题】:Aggregate, lookup from 2 collections and extract the result聚合,从 2 个集合中查找并提取结果
【发布时间】:2019-04-09 13:52:19
【问题描述】:

我在使用 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" 中提取在 "testScriptResultCollection" 上查找每个记录的结果(通过 testCaseIdtestScriptId 来获取其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

任何人都可以帮助我吗?非常感谢。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案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 }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 2014-01-25
      • 1970-01-01
      • 2014-02-23
      • 2018-04-23
      • 2019-01-30
      • 2019-12-30
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多