Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a deep nested object in mongodb

Tags:

mongodb

Say I have a document that represents books like this:

{
   "_id":"1234567890",
   "title":"Lord Of The Rings",
   "books": {
      "1234567890":{
         "_id":"123456789890",
         "title":"The Two Towers",
         "page_count":{
            "en":6000,
            "de":7000
         }
      },
      "2234567890":{
         "_id":"223456789890",
         "title":"The Return Of The King",
         "page_count":{
            "en":6000,
            "de":7000
         }
      },
   }
}

How would I go about removing the page count for the 2nd book? I tried

{$unset : {"books.2234567890.page_count":""}}

Didn't work. Any ideas?

Thanks a lot

like image 293
JohnE Avatar asked Jan 20 '13 02:01

JohnE


1 Answers

I took a stab at it and it looks like what you are trying to do should work correctly. I would check your query to locate the proper document to update and make sure it's finding what you want.

> db.books.findOne()
{
        "_id" : "1234567890",
        "title" : "Lord Of The Rings",
        "books" : {
                "1234567890" : {
                        "_id" : "123456789890",
                        "title" : "The Two Towers",
                        "page_count" : {
                                "en" : 6000,
                                "de" : 7000
                        }
                },
                "2234567890" : {
                        "_id" : "223456789890",
                        "title" : "The Return Of The King",
                        "page_count" : {
                                "en" : 6000,
                                "de" : 7000
                        }
                }
        }
}
> db.books.update({'_id': "1234567890"}, {$unset: {'books.2234567890.page_count': ""}})
> db.books.findOne()
{
        "_id" : "1234567890",
        "books" : {
                "1234567890" : {
                        "_id" : "123456789890",
                        "title" : "The Two Towers",
                        "page_count" : {
                                "en" : 6000,
                                "de" : 7000
                        }
                },
                "2234567890" : {
                        "_id" : "223456789890",
                        "title" : "The Return Of The King"
                }
        },
        "title" : "Lord Of The Rings"
}
>
like image 133
mgoffin Avatar answered Oct 10 '22 10:10

mgoffin