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获取testscriptname)和“memberscoollection”(通过userid获取用户名)中提取查找“testscriptresultcollection”上每个记录的结果
我想要的结果是:
[
{
_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
有人能帮我吗?非常感谢。
最佳答案
您可以使用下面优化的聚合管道
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 }}
])
关于mongodb - 聚合,从2个集合中查找并提取结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53167359/