mongodb update/upsert that adds data to the existing document instead of replacing data in an existing document

788 Views Asked by At

I am using an upsert using mongodb's Jensseger PHP library. Every time I add new data to the document it updates the value of the field if the field names are the same. I want to add to the document's data instead of replacing it.

An example of a record in my session_activities collection:

"_id" : ObjectId("622f8da565fbcea0a1b4ed12"),
"activity" : [
                {
                        "name" : "Fullscreen Off",
                        "time" : 219.972769,
                        "value" : 0
                },
                {
                        "name" : "Player Resize",
                        "time" : 220.074389,
                        "value" : 354
                },
                {
                        "name" : "close",
                        "time" : 223.779885,
                        "value" : 369
                }
        ]

If that record has a new "Player Resize" event at 500 seconds I want the document to change to:

  "_id" : ObjectId("622f8da565fbcea0a1b4ed12"),
        "activity" : [
                        {
                                "name" : "Fullscreen Off",
                                "time" : 219.972769,
                                "value" : 0
                        },
                        {
                                "name" : "Player Resize",
                                "time" : 220.074389,
                                "value" : 354
                        },{
                                "name" : "Player Resize",
                                "time" : 500,
                                "value" : 354
                        },
    
                        {
                                "name" : "close",
                                "time" : 223.779885,
                                "value" : 369
                        }
                ]

Right now the Player Resize field is being overwritten with the new value. My mongo statement looks like the below:

(new VideoAnalytics)->where($whereStatement)->update($this->newobj, ['upsert' => true])
2

There are 2 best solutions below

4
Jijo Alexander On

If you give the entire object with the key values you provided into the MongoDB update method it will replace the whole record, instead of that please start using $set in MongoDB to set the specific keys. Here also I'm adding a reference link for better understanding.

https://php.uz/manual/en/mongocollection.update.php

new VideoAnalytics->update(
    $whereStatement,
    array('$set' => $this->newobj),
    array('upsert' => true)
);
0
PepeNietnagel On

as I understand, you wanna update by pushing a new element to the array, right?

this might help push new value to mongodb inner array - mongodb/php