Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB/PHP: delete element from array

Tags:

php

mongodb

pull

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,

like image 660
Eamorr Avatar asked Dec 05 '22 00:12

Eamorr


1 Answers

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.

like image 92
svjson Avatar answered Dec 23 '22 10:12

svjson