How to remove deeply nested object in mongodb

Let's say I have a document that presents 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 can I delete the page count for the second book? I tried

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

      

Does not work. Any ideas?

Thank you so much

+3


source to share


1 answer


I took a hit from it and it looks like what you are trying to do should work correctly. I would check your request to find a suitable update document and make sure it finds 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"
}
>

      

+7


source







All Articles