'MongoDB simply merge two unknown Documents

Is there a way in PHP Mongodb to write an object in an already existing document and only overwrite or add the values contained in the object.

The object structure is not known to me.

Here is a sample:

existing document:

{
  "package": {
    "parameter": "value",
    "one": "two"
  }
}

php object or array:

$obj[package][parameter] = "value2" 
$obj[package][new] = "test"`

result schould be

{
  "package": {
    "parameter": "value2",
    "one": "two",
    "new": "test"
  }
}

I need something like array_merge()

I tried the $merge aggerator but it does not seem to work.

Unknown modifier: $merge. Expected a valid update modifier or pipeline-style update specified as an array



Solution 1:[1]

$merge is used to insert/update document to collection, like the UPSERT command in SQL. Have a look at $mergeObjects. Use it in combination with $replaceWith (or $replaceRoot which is just an alias)

Would be something like

{ $replaceWith: { $mergeObjects: [ "$$ROOT", {"new" : "test"} ] } }

$$ROOT is the existing object. If the existing object has any fields with the same name as your new object, then it will be overwritten with new field values. If you like to prefer the existing fields, then flip the arguments in the array.

The sample data you provided is not valid JSON, thus I cannot provide a full solution.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wernfried Domscheit