I need to add a completed attribute using addField aggregate query, if the orders array inside a collection (sales) contains an object with status attribute having value delivered.
db.sales.insertMany([
{
"_id" : 1,
"salesId" : "2938432",
"customerId" : "987677789",
"amount:"23000"
"orders":[{
orderId:"TX8383428979382",
status:"cancelled"
},
{
orderId:"TX8383428979383",
status:"fullfilled"
}]
},
{
"_id" : 1,
"salesId" : "2938433",
"customerId" : "987676578",
"amount:"13000"
"orders":[
{
orderId:"TX838342892437363",
status:"placed"
}]
},
.........
)]
My aggregate query
db.sales.aggregate([
{$match:{....}},
{$addFields:{
completed: {
$cond: { if: { /* code to check if orders array contains an object with `status:fullfilled` }, then: true, else: false }
}
}},
])
How can I check for a match for an attribute inside array of objects.?
$addFieldsstage.$mapwill let you iterate over theordersarray and you can check each element of the array for the condition and add a new attribute when there is match.completedattribute? For the "orders" sub-document or the root/top level?