I have followed the below SO thread but still not functioning.
MongoDB Join on multiple fields [duplicate]
Multiple join conditions using the $lookup operator
My collection1
is as below:
{
_id: 5bc2e44a106342152cd83e97,
description:
{
status: 'Good',
machine: 'X',
},
order: 'A',
lot: '1'
}
My collection2
is as follow:
{
_id: 5bc2e44a106342152cd83e80,
isCompleted: false,
serialNo: '1',
batchNo: '2',
product: [{
order: 'A', lot: '1',
order: 'A', lot: '2'
}]
}
the result i expect is as follow:
{
_id: 5bc2e44a106342152cd83e97,
description:
{
status: 'Good',
machine: 'X',
},
order: 'A',
lot: '1' ,
isCompleted: false,
serialNo: '1',
batchNo: '2'
}
The aggregation operation has to be based on the condition where product
array in collection2
contains the order
and lot
that is the same with the order
and lot
in collection1
.
Below are 2 codes that I have tried but to no avail. May I have some guidance.
db.collection2.aggregate([
{ $unwind : "$product" }
{
$lookup: {
from: "collection1",
localField: "product.order",
foreignField: "order",
as: "results"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$results", 0 ] }, "$$ROOT" ] } }
}]
Then, I tried the multiple join condition based on the docs, but no luck
db.collection2.aggregate([
{ $unwind : "$product" },
{ $lookup: {
from: "collection1",
let: { order: "$order", lot: "$lot" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: [ "$product.order", "$$order" ] },
{ $eq: [ "$product.lot", "$$lot"] }
]
}
}
}
],
as: "results"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$results", 0 ] }, "$$ROOT" ] } }
}]
Any hints or guidance or solution will be greatly appreciated! Thanks!