I have 2 collections, ratePlans and properties.
Properties has an array of cancelPolicies as a subdocument and ratePlans has cancelPolicyId to reference this.
I am trying to lookup the cancellation policy for a given ratePlan.
$lookup: {
from: "properties",
let: { propertyId: "$propertyId", cancelPolicyId: "$cancelPolicyId" },
pipeline: [
{
$match: { $expr: { $eq: [ "$_id", "$$propertyId" ] } }
},
{
$unwind: {
path: "$cancelPolicies",
preserveNullAndEmptyArrays: true
}
},
{
$match: { $expr: { $eq: [ "$cancelPolicies._id", "$$cancelPolicyId" ] } }
},
// I tried this, but it does nothing. I also tried putting it after replaceRoot:
// {
// $unwind: {
// path: "$cancelPolicies",
// preserveNullAndEmptyArrays: true
// }
// },
{
$replaceRoot: { newRoot: "$cancelPolicies" }
},
],
as: "cancelPolicy"
}
This works, however cancelPolicy is now an array of length 1 instead of an object. Is it possible to have cancelPolicy be the actual object instead of an array?