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
What is MongoDB $unwind? The MongoDB $unwind operator is used to deconstruct an array field in a document and create separate output documents for each item in the array.
For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents. For example, if a user requires all grades from all students, then the below query can be written: Students.
Hi, Yes, you can join 2 collections with Aggregation Framework and $unionWith stage. Here are the docs with syntax and examples, so you can check how to do it.
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"
}}
])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With