4

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 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What if you were certain it was the right index of the notifications array? How could you identify the array item then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.