Collection in the database:
{
"value": {
"shipmentId": 1079,
"customer_orders": [
{
"customer_order_id": 1124,
"active": false
},
{
"customer_order_id": 1277,
"active": true,
"items": [
{
"item_id": 281,
"active": false,
"qty": 1,
"name": "apples",
"attributes": null
},
{
"item_id": 282,
"active": true,
"qty": 2,
"name": "bananas"
}
]
}
],
"carrier_orders": [
{
"carrier_order_id": 744,
"active": true
}
]
}
}
Query:
db.getCollection('shipments').aggregate([
{
"$match": {
"value.shipmentId": {
"$in": [
1079
]
}"
}
},
{
"$project": {
"value.shipmentId": 1,
"value.customer_orders": 1,
"value.carrier_orders": 1,
}
},
{
"$addFields":{
"value.customer_orders":{
$filter:{
input: "$value.customer_orders",
as: "customer_order",
cond: {
$eq: ["$$customer_order.active", true]
}
}
},
"value.customer_orders.items":{
$filter:{
input: "$value.customer_orders.items",
as: "item",
cond: {
$eq: ["$$item.active", true]
}
}
},
"value.carrier_orders": {
$filter:{
input: "$value.carrier_orders",
as: "carrier_order",
cond: {
$eq: ["$$carrier_order.active", true]
}
}
}
}
}
]
);
Desired output:
{
"value": {
"shipmentId": 1079,
"customer_orders": [
{
"customer_order_id": 1277,
"active": true,
"items": [
{
"item_id": 282,
"active": true,
"qty": 2,
"name": "bananas"
}
]
}
],
"carrier_orders": [
{
"carrier_order_id": 744,
"active": true
}
]
}
}
I am trying to apply filters at two different levels:
- “value.customer_orders”
- “value.customer_orders.items”
What I want is to filter out inactive customer orders, and within active customer orders, filter out inactive items. While doing this, if there are any attributes at the customer order level, we want to retain them too in the output.
How can I achieve this multi-level nesting of conditions and retain attributes using the aggregate pipeline?