Reputation: 83
I currently need to perform a query with MongoDB using the aggregation framework. Here is the diagram of my documents as well as the request I wish to make.
tools
{
"_id": 1,
"code": "TOOL_1",
"label": "Tool 1",
"items": [
{
"code_it": TOOL_1_TT_1,
"label": "Tool TT 1",
"value": 25.00
},
{
"code_it": TOOL_1_TT_2,
"label": "Tool TT 2",
"value": 17.00
},
{
"code_it": TOOL_1_TT_3,
"label": "Tool TT 3",
"value": 17.00
},
]
}
results_tools
{
"_id": 1,
results: [
{
"code_it": "TOOL_TT_2",
"owner": "person_A"
},
{
"code_it": "TOOL_TT_3",
"owner": "person_D"
},
{
"code_it": "TOOL_TT_2",
"owner": "person_C"
},
]
}
db.results_tools.aggregate([
{ $unwind: "$results" },
{
$lookup: {
from: "tools",
let: { res_cod_it: "$code_it" },
pipeline: [
{ $unwind: "$items" },
{
$match: {
$expr: {
$eq: [ "$$res_cod_it", "$code_it" ]
}
}
}
],
as: "item"
}
},
{
$project: {
"owner": 1,
"el.code": "code_it",
"el.label": "item.label",
"el.value": "item.label"
}
}
]);
I would like to be able to retrieve the label of the tool based on the results. However, I have an error at runtime, so I wonder if using $unwind in the $lookup pipeline is possible.
Thank you for your answer. Laurent
Upvotes: 8
Views: 19076
Reputation: 75984
You can use below pipeline. Note the use of dot notation to reference the array fields.
db.results_tools.aggregate([
{"$unwind":"$results"},
{"$lookup":{
"from":"tools",
"let":{"res_cod_it":"$results.code_it"},
"pipeline":[
{"$unwind":"$items"},
{"$match":{"$expr":{"$eq":["$$res_cod_it","$items.code_it"]}}}
],
"as":"item"
}},
{"$unwind":"$item"},
{"$project":{
"owner":"$results.owner",
"code":"$item.items.code_it",
"label":"$item.items.label",
"value":"$item.items.value"
}}
])
Upvotes: 15