0

如何删除该特定用户的“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":[

         ]
      }
   ],
}

4

2 回答 2

2

尝试将elemMatch$结合使用:

db.books.update(
    {
        books: {
            $elemMatch: {
                "id_book": 8522, 
                "extras.id_extra": 8523
            }
        },
        user_id: 258787       
    }, 
    {
        $pull: {
            "books.$.extras": {
                "id_extra": 8523
            }
        }
   }
)
于 2020-02-01T15:20:58.323 回答
0

你可以这样做:"extras" with "id_extra = 8523" of the "book" "id_book = 8522"在 MongoDB 中再次过滤和保存文档

db.collection.aggregate([
  {
    $match: {
      "books.id_book": 8522
    }
  },
  {
    $addFields: {
      "books": {
        $reduce: {
          input: "$books",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              [
                {
                  _id: "$$this._id",
                  id_book: "$$this.id_book",
                  blob_annotation: "$$this.blob_annotation",
                  extra_id: "$$this.extra_id",
                  raccolte: "$$this.raccolte",
                  extras: {
                    $filter: {
                      input: "$$this.extras",
                      cond: {
                        $ne: [
                          "$$this.id_extra",
                          8523
                        ]
                      }
                    }
                  }
                }
              ]
            ]
          }
        }
      }
    }
  }
])

Mongo游乐场

于 2020-02-01T13:44:40.820 回答