【发布时间】:2020-05-06 13:46:45
【问题描述】:
我在使用 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" 查找 2 个集合,并找到类似 testScriptId 的 "name",但它出错了
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]}
}
}
}
}
]}
谁能帮帮我。任何帮助,将不胜感激。非常感谢。
【问题讨论】:
-
你好你可以试试这个查询,但这不是最好的方法:docs.google.com/document/d/…
-
答案有问题吗?
-
不是最好的方法,但可以正常工作,感谢您的帮助。
标签: mongodb mongodb-query aggregation-framework