我在MongoDB中有json对象。我想为此对象添加值,例如在位置 - >机器 - >传感器。我知道机器的_id,位置和传感器。这样做最有效的方法是什么?
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 (
)
)
)
)
)
)
)
答案 0 :(得分:0)
超级简单。您可以拨打findAndModify电话。或者如果你想手动更多一点,你可以这样做:
$collection = $mongo->your_collection;
$obj = $collection->findOne($query);
$obj = $obj['locations']['machines']['sensors'][] = $new_sensor;
$collection->save($obj);
Mongo足够聪明,可以使用_id
键识别对象,从而将这些存储视为对现有对象的更新。没有它,你就可以用它创建新的对象。