Home > Software engineering >  How can I use $mergeObjects with an optional property?
How can I use $mergeObjects with an optional property?

Time:10-07

I'm writing an aggregation below. The purpose of the aggregation is to replace the value of targetedProperty, but only if targetedProperty already exists, targetedProperty being an optional property on objectToUpdate.

How would I adjust this code to do this?

{
    $set: {
        objectToUpdate: {
            $mergeObjects: [
                '$objectToUpdate',
                {
                    targetedProperty: {
                        $cond: {
                             if: { $lte: ['$objectToUpdate.targetProperty', null] }, 
                             then: undefined, 
                             else: 'newValue'
                        }
                    },
                },
            ],
        },
    },
}

This is an example of an input:

{ otherProperty: 'value', anotherProperty: 'anotherValue' }

This is my expected result:

{ otherProperty: 'value', anotherProperty: 'anotherValue' }

This is my actual result:

{ otherProperty: 'value', anotherProperty: 'anotherValue', targetedProperty: null }

Note: I do have to do this as an aggregation because I am making use of additional aggregation operators in parts of the logic not shown here.

CodePudding user response:

You need to change the order of your $cond, we first check if the field "targetedProperty" exists, if it doesn't we'll put the empty object {} for the $mergeObjects operator, meaning we won't update the object at all, If the field does exists then we'll just put the relevant value, like so:

db.collection.aggregate({
  $set: {
    objectToUpdate: {
      $mergeObjects: [
        "$objectToUpdate",
        {
          $cond: [
            {
              $eq: [
                "$objectToUpdate.targetedProperty",
                undefined
              ]
            },
            {},
            {
              targetedProperty: 123
            }
          ]
        }
      ]
    }
  }
})

Mongo Playground

  • Related