0

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.?

3
  • You can use the $map aggregation operator with the $addFields stage. $map will let you iterate over the orders array and you can check each element of the array for the condition and add a new attribute when there is match. Commented Apr 21, 2020 at 8:27
  • Thanks @prasad_. Seems like i can $reduce also. But I am unable to put it to code. Would be really helpful if u can put an example Commented Apr 21, 2020 at 10:30
  • Where do you want to add the completed attribute? For the "orders" sub-document or the root/top level? Commented Apr 21, 2020 at 10:46

1 Answer 1

2

Here is the aggregation which uses the $reduce array operator to add a new attribute completed which is derived based upon the orders.status "delivered".

db.sales.aggregate( [
{
    $addFields: {
        completed: {
            $reduce: {
                input: "$orders", initialValue: false,
                in: {
                     $cond: [ { $eq: [ "$$this.status", "delivered" ] }, 
                                true, 
                                "$$value"
                     ]
                }
            }
        }
    }
}
] ).pretty()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.