'MongoDB: pullAll / pull whole nested array object by value using mongoose

I want to pull the whole nested array object if the object contains a specified string for a specific key. I'm using mongoose with nodejs:

DB before deletion:

{ _id : 1234
   fallBackData: {
      nestedKey: [ { arrayKey: "theValue" }, { arrayKey: "anotherValue" } ]
   }
 }

DB after deletion:

{ _id : 1234
   fallBackData: {
      nestedKey: [ { arrayKey: "anotherValue" } ]
   }
 }

I took a look at How can I pull nested object value in mongodb and $pullAll Mongo DB docs ,tried the following, but none worked:

 const ad = await Ad.updateOne(
     { _id: 1234 },
     {
         $pullAll: {
             fallbackData: { nestedKey: [{ arrayKey: "theValue"}] },
         },
     }
 );

 const ad = await Ad.updateOne(
     { _id: 1234 },
     {
         $pullAll: {
             "fallbackData.$.nestedKey" : { arrayKey: "theValue" },
         },
     }
  );

  const ad = await Ad.updateOne(
      { _id: 1234 },
      {
          $pullAll: {
              "fallbackData.$.nestedKey" : [{ arrayKey: "theValue"}],
          },
      }
  );

The query return value is the following, but the object in the array is not deleted:

 {
   acknowledged: true,
   modifiedCount: 1,
   upsertedId: null,
   upsertedCount: 0,
   matchedCount: 1
 }


Solution 1:[1]

You can achieve this by changing a little

playground

db.collection.update({
  _id: 1234,
  "fallBackData.nestedKey": {
    $elemMatch: {
      "arrayKey": "theValue"
    }
  }
},
{
  "$unset": {
    "fallBackData": "nestedKey"
  }
})

You cannot add matching conditions with $pullAll related to Array

$pullAll expects an array of matching values to be removed

You can do $pull instead of $unset but $pull results empty array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gibbs