Add value to object in MongoDB

I have a json object in MongoDB. I want to add value to this object, for example in places -> cars -> 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 (
                            )
                        )
                    )
                )
            )
        )
    )

      

+3


source to share


1 answer


Super lightweight. You can either call findAndModify . Or, if you want to do it a little 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 an object using a key _id

that makes it treat those values ​​as updates to existing objects. Without it, you will be creating new objects with this.

0


source







All Articles