MongoDB/PHP: delete element from array

十年热恋 提交于 2019-11-30 17:51:12

问题


Greetings,

I have the following MongoDB object:

{
   "_id": ObjectId("4d0e28938b012fe28754715a"),
   "notifications": {
     "0": {
       "type": "privateMessage",
       "fromUname": "Eamorr2",
       "time": 1292773522,
       "id": "1lfw70h789u13a1e67pv"
    },
    "1": {
       "type": "privateMessage",
       "fromUname": "Eamorr2",
       "time": 1292773522,
       "id": "iwoidjsoskqp23nlwof"
    }
  },
   "toUname": "Eamorr"
}

I'm trying to delete element 0, to leave me with:

{
   "_id": ObjectId("4d0e28938b012fe28754715a"),
   "notifications": {
    "0": {
       "type": "privateMessage",
       "fromUname": "Eamorr2",
       "time": 1292773522,
       "id": "iwoidjsoskqp23nlwof"
    }
  },
   "toUname": "Eamorr"
}

Here's what I've tried sofar (in PHP), to no avail:

$customerNotifications->update(array('toUname'=>$uname),array('$pull'=>array('notifications'=>$key)));

But it's not working and I'm totally stuck now.

Any help much appreciated. Thanks in advance,


回答1:


Eamorr,

The $pull operator will not work on the document you are using, because the "notifications"-key is not really an array. It is rather an embedded document, with numbered keys, making it superficially resemble an array. There is no way (that I know of) to keep this document structure and have the numbered keys renamed automatically.

If you refactor your document slightly, to look like this:

{
   "notifications": [
    {
       "type": "privateMessage",
       "fromUname": "Eamorr2",
       "time": 1292773522,
       "id": "1lfw70h789u13a1e67pv"
    },
    {
       "type": "privateMessage",
       "fromUname": "Eamorr2",
       "time": 1292773522,
       "id": "iwoidjsoskqp23nlwof"
    }
  ],
   "toUname": "Eamorr"
}

The elements will still be numbered, implicitly. It's now an array, so you get that for free. You can use the $pull operator like this (I am not familiar with the PHP-driver, so I'm giving you the shell equivalent):

db.messages.update({ "toUname" : "Eamorr" }, { $pull : { "notifications" : { "id" : "1lfw70h789u13a1e67pv" }}});

I arbitrarily used the "toUname" key to identify the document, but I guess you will be wanting to use the _id-field. Also, I'm using the "id"-key of the messages to identify the message to pull from the array, as it is a lot safer and makes sure you don't accidentally remove the wrong message in case the array has changed since you identified the array ordinal to remove.

I hope that helps.



来源:https://stackoverflow.com/questions/4483897/mongodb-php-delete-element-from-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!