MongoDB/PHP: delete element from array

前端 未结 1 476
北海茫月
北海茫月 2021-01-06 05:22

Greetings,

I have the following MongoDB object:

{
   \"_id\": ObjectId(\"4d0e28938b012fe28754715a\"),
   \"notifications\": {
     \"0\": {
       \"         


        
相关标签:
1条回答
  • 2021-01-06 05:50

    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.

    0 讨论(0)
提交回复
热议问题