douduidui1046 2012-09-20 09:22
浏览 29
已采纳

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

The contents of my mongodb collection are in the form of

{
"_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"
    }
 ]
}

I am trying to add another address details inside the collection, so that the content will become,

{
 "_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"
   } 
 ]
}

Here is the code I have written to update address field.

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

But this code is not updating the contents, Meanwhile it deletes the whole record. and the exception message I got is,

  Fatal error: Uncaught exception 'MongoCursorException' with message 'false'

The "addresses" I have is an embedded object. I am wondering whether we can use 'addToSet' on embedded object.

Where I am going wrong?

  • 写回答

2条回答 默认 最新

  • doue9730 2012-09-20 09:39
    关注

    Have you try following way to update?

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

报告相同问题?

悬赏问题

  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法