0

我的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” 。

我哪里错了?

4

2 回答 2

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);
于 2012-09-20T09:39:51.837 回答
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用于删除一个字段。

于 2012-09-20T09:59:20.823 回答