I am evaluating MongoDB for an application and I am trying to learn how to use it.
I don't know whether what I want to achieve is possible, so I am prepared for "No" as an answer.
Suppose the three collections described below (in mongoplayground-style format)
db={
packages: [
{
_id: 10,
name: "small box"
},
{
_id: 20,
name: "big box"
}
],
shipments: [
{
customer: "bob",
items: [
{
_id: 12312,
package_id: 20,
weight: 9.99,
},
{
_id: 65489,
package_id: 10,
weight: 1.5
}
]
}
]
}
I want to use the aggregation framework to produce a document a shipment, where for each item a new property is added that contains the information regarding the package (example given below)
{
customer: "bob",
items: [
{
_id: 12312,
package_id: 20,
weight: 9.99,
package: {
_id: 20,
name: "big box"
}
},
{
_id: 65489,
package_id: 10,
weight: 1.5,
package: {
_id: 10,
name: "small box"
}
}
]
}
I have tried using $lookup without a pipeline, but I can only get up to a point where I replace each item document with the corresponding package document (which of course is not what I want to achieve), and I am lost with using $lookup with a pipeline (which if I were a betting man, I'd bet is the way to achieve what I want). I kind of got somewhere by $unwind'ing the items array, followed by a $lookup and a $group / $push but then I am not sure how to retrieve the other fields of a shipment document other than the items (and I have a feeling this is not the proper way to achieve the desired result).
I can post more code if needed (what I have tried so far), but I am trying to keep the question within a reasonable length
Any help would be appreciated, as I am sure I could be trying for days to produce the sample I want and I am not even sure it is possible.