Updating element of array with parent object value

Original Collection:

{
  'name': 'apple',
  'total': 20,
  'baskets': [ 
   {   
      'name': 'basket_green',
      'total': 0
    }
  ]
}

How to update ‘baskets’ array with a new element which would take ‘total’ from object.
So the resulting collection should look like:

{
  'name': 'apple',
  'total': 20,
  'baskets': [
    {   
      'name': 'basket_green',
      'total': 20
    }
  ]
}

MongoDB Server 5.0

I tried updating with $set operator with positional operator ‘$’. But it is not working as expected. The literal string ‘$total’ is getting set to array element ‘basket_green’.

1 Like

I tried with this command:

db.collection.update(
    { 
        $and: [
            { 'name': 'apple' },
            { 'baskets.$.name': 'basket_green' }
        ]
    }
    { 
        $set: {
            'baskets.$.total': '$total'
        }
    }
)

I’m not properly referring to parent ‘total’ value which otherwise could have set to the value outside array correctly.

Hi,

You can do it easily with Aggregation Framework:

db.collection.update({},
[
  {
    "$set": {
      "baskets.total": "$total"
    }
  }
])

Working example

1 Like

Hey @NeNaD
Thank you for providing the working example.
That works as desired.
I wonder what if we just need to update single basket?
I tried specifying filters but it doesn’t have any effect.

Hi,

In that case you can do something like this:

  • $map with $cond - to map baskets array based on condition
  • $eq - to check if name property matches the name of basket that needs to be updated. If it matches update it with the total value of the cart. If it does not match do nothing.
db.collection.update({},
[
  {
    "$set": {
      "baskets": {
        "$map": {
          "input": "$baskets",
          "as": "basket",
          "in": {
            "$cond": {
              "if": {
                "$eq": [
                  "$$basket.name",
                  "basket_blue"
                ]
              },
              "then": {
                "name": "$$basket.name",
                "total": "$total"
              },
              "else": "$$basket"
            }
          }
        }
      }
    }
  }
])

Working example

1 Like

Thanks it is NOW perfect! :slight_smile:
Can you please share a link where I can learn more about this?
Basic Aggregation topic in MongoDB Documentation? Or any other more sane resource?

Hi,

I guess you can check the official MongoDB courses. Also, Stack Overflow is a great place to find solutions to common challenges.

2 Likes

I highly appreciate this. :man_bowing:

1 Like

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