How to combine $set and $cond? Or use other operator?

How can I update a field when a condition is met?

if option.returned is true I want to update the field status:'returned'.

orders: [
    { id: 100, status: "shipped", options: [{ returned: true }] },
    { id: 101, status: "packed", options: [{ quick: true }] },
    { id: 102, status: "ordered" }
]

desired result: [
    { id: 100, status: "returned", options: [{ returned: true }] },
    //                  ^- updated status because returned: true
    { id: 101, status: "packed", options: [{ quick: true }] },
    { id: 102, status: "ordered" }
]

I can set an additional field returned, extracting the value from the array into the field.

  {
    $set: {
      returned: "$options.returned"
    }
  },
  {
    $unwind: {
      path: "$returned",
      preserveNullAndEmptyArrays: true
    }
  }

orders: [
    { id: 100, status: "shipped", options: [{ returned: true }], returned: true }, // extracted value from array
    { id: 101, status: "packed", options: [{ quick: true }] },
    { id: 102, status: "ordered" }
]

But so far all attempts combining $set and $cond to overwrite status have failed for me.

How can I update status when returned is set, otherwise keep the previous value?

MongoDB Playground

Thanks,
bluepuma

I tried to use $if, of course that didn’t work.

db.orders.aggregate([
  {
    $set: {
      status: {
        $cond: {
          if: {
            $arrayElemAt: [
              "$options.returned",
              0
            ]
          },
          then: "returned",
          else: "$status"
        }
      }
    }
  }
])
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.