繁体   English   中英

Mongodb / PHP更新,删除集合中的记录并抛出异常。 为什么?

[英]Mongodb/PHP update, deletes a record in the collection and throws exception. why?

我的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'

我哪里错了?

您是否尝试过以下方式进行更新?

$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);

$addToSet用于将字段附加到数组(如果它尚不存在)。

你应该做的是使用$set update修饰符:

$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用于删除字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM