如何删除mongodb中的深层嵌套对象

2024-03-01

假设我有一个代表这样的书籍的文档:

{
   "_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
         }
      },
   }
}

我将如何删除第二本书的页数?我试过

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

没用。有任何想法吗?

多谢


我尝试了一下,看起来您正在尝试做的事情应该可以正常工作。我会检查您的查询以找到要更新的正确文档,并确保它找到您想要的内容。

> 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"
}
>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何删除mongodb中的深层嵌套对象 的相关文章

随机推荐