我的mongodb集合的内容是
的形式{
"_id" : ObjectId("50072668b4a6de94100000bb"),
"addresses" : [
{
"_id" : ObjectId("50072668b4a6de94100000bf"),
"address1" : "66 Wadsworth Park Dr",
"address2" : null,
"city" : "Draper",
"country" : "United States",
"country_code" : "US",
"name" : "main",
"primary" : true,
"state" : "Utah",
"zip" : "84020"
}
]
}
我正在尝试在集合中添加另一个地址详细信息,以便内容成为,
{
"_id" : ObjectId("50072668b4a6de94100000bb"),
"addresses" : [
{
"_id" : ObjectId("50072668b4a6de94100000bf"),
"address1" : "66 Wadsworth Park Dr",
"address2" : null,
"city" : "Draper",
"country" : "United States",
"country_code" : "US",
"name" : "main",
"primary" : true,
"state" : "Utah",
"zip" : "84020"
}
{
"_id" : ObjectId("50072668b4a6de9410000023"),
"address1" : "a",
"address2" : "b",
"city" : "c",
"country" : "d",
"country_code" : "d",
"name" : "e",
"primary" : "f",
"state" : "g",
"zip" : "h"
}
]
}
以下是我为更新地址字段而编写的代码。
$add_address = array('$addToSet' => array("addresses" => array("_id" => new MongoId(), "address1" => $address1, "address2" => $address2, "city" => $city, "country" => $country, "country_code" => $country_code, "name" => $name, "primary" => $primary, "state" => $state, "zip" => $zip)));
$mycollection->update(array("_id" => new MongoId($id)), $add_address);
但是这段代码没有更新内容,同时它删除了整个记录。 我收到的异常消息是,
Fatal error: Uncaught exception 'MongoCursorException' with message 'false'
我拥有的“地址”是一个嵌入式对象。我想知道我们是否可以在嵌入对象上使用'addToSet'。
我哪里错了?
答案 0 :(得分:1)
您是否尝试过以下方式进行更新?
$add_address = array('$set' => array("addresses" => array("_id" => new MongoId(), "address1" => $address1, "address2" => $address2, "city" => $city, "country" => $country, "country_code" => $country_code, "name" => $name, "primary" => $primary, "state" => $state, "zip" => $zip)));
$mycollection->update(array("_id" => new MongoId($id)), $add_address);
答案 1 :(得分:1)
$addToSet
用于将字段附加到数组(如果它尚不存在)。
您应该使用$set
更新修饰符:
$add_address = array('addresses' => array("_id" => new MongoId(), "address1" => $address1, "address2" => $address2, "city" => $city, "country" => $country, "country_code" => $country_code, "name" => $name, "primary" => $primary, "state" => $state, "zip" => $zip));
$mycollection->update( array( array("_id" => new MongoId($id) ), array('$set' => $add_address) );
$unset
用于删除字段。