首页 > 解决方案 > 如何删除子子文档mongoosejs中的元素

问题描述

如何删除该特定用户的“book”“id_book = 8522”的“id_extra = 8523”的“extras”?,我目前使用mongoosejs但我没有成功,我尝试了很多东西,但我尝试的是工作到嵌套文档的第一级。

{
   "_id":{
      "$oid":"5e32fce08919b53ad66cf694"
   },
   "user_id":{
      "$numberInt":"258787"
   },
   "username":"daaaa",
   "firstname":"davide",
   "api_key":"7b031c21edf1237c554867622ad1154f",
   "books":[
      {
         "_id":{
            "$oid":"5e356323a0ef6319ebb60162"
         },
         "id_book":{
            "$numberInt":"8522"
         },
         "blob_annotation":null,
         "extra_id":{
            "$numberInt":"995176"
         },
         "extras":[
            {
               "_id":{
                  "$oid":"5e356324a0ef6319ebb60163"
               },
               "id_extra":{
                  "$numberInt":"8523"
               },
               "type":"gallery_audio",
               "label":"Inverno a Boscodirovo"
            },
            {
               "_id":{
                  "$oid":"5e356324a0ef6319ebb60164"
               },
               "id_extra":{
                  "$numberInt":"8524"
               },
               "type":"gallery_audio",
               "label":"Storia di Primavera"
            }
         ],
         "raccolte":[

         ]
      }
   ],
}

标签: javascriptnode.jsmongodbmongoose

解决方案


尝试将elemMatch$结合使用:

db.books.update(
    {
        books: {
            $elemMatch: {
                "id_book": 8522, 
                "extras.id_extra": 8523
            }
        },
        user_id: 258787       
    }, 
    {
        $pull: {
            "books.$.extras": {
                "id_extra": 8523
            }
        }
   }
)

推荐阅读