Search code examples
phpmongodbphp-mongodb

Add value to object in MongoDB


I have json object in MongoDB. I want to add a value to this object, for example in locations -> machines -> sensors. I know the _id for the machine, for the location and for the sensor. What is the most efficient way to do this?.

    array(
    "_id" => '547f2e4cb54b3a96203c9869',
    "name" => Array (
        "nl" => "klant1"
    ),
    "locations" => Array (
        Array (
            "_id" => "1",
            "name" => Array (
                "nl" => "location1",
            ),
            "machines" => Array (
                Array (
                    "_id" => "1",
                    "name" => Array (
                        "nl" => "boot1"
                    ),
                    "sensors" => Array (
                        Array (
                            "_id" => "1",
                            "log" => Array (
                            )
                        ),
                        Array (
                            "_id" => "2",
                            "log" => Array (
                            )
                        )
                    )
                ),
                Array (
                    "_id" => "2",
                    "name" => Array (
                        "nl" => "boot2"
                    ),
                    "sensors" => Array (
                        Array (
                            "_id" => "1",
                            "log" => Array (
                            )
                        ),
                        Array (
                            "_id" => "2",
                            "log" => Array (
                            )
                        )
                    )
                ), 
                Array (
                    "_id" => "3",
                    "name" => Array (
                        "nl" => "boot3"
                    ),
                    "sensors" => Array (
                        Array (
                            "_id" => "1",
                            "log" => Array (
                            )
                        ),
                        Array (
                            "_id" => "2",
                            "log" => Array (
                            )
                        )
                    )
                )
            )
        )
    )

Solution

  • Super easy. You can either do a findAndModify call. Or if you want to do it a little more manually, you can do:

    $collection = $mongo->your_collection;
    $obj = $collection->findOne($query);
    $obj = $obj['locations']['machines']['sensors'][] = $new_sensor;
    $collection->save($obj);
    

    Mongo is smart enough to identify the object using _id key which causes it to treat these saves as updates to existing objects. Without it you'd be creating new objects with this.