Home > Back-end >  MongoDB not pulling from array when no filter is given
MongoDB not pulling from array when no filter is given

Time:09-22

Weird behavior : my pull operation only works when I specify a filter that only matches exactly one document.

My goal is to delete all instances whose owner id is equal to a certain value.

Here is my data sample

[
  {
    "id": 1,
    "instances": [
      {
        "id": 2,
        "owner": {
          "id": 2
        }
      }
    ]
  },
  {
    "id": 2,
    "instances": [
      {
        "id": 1,
        "owner": {
          "id": 1
        }
      },
      {
        "id": 4,
        "owner": {
          "id": 2
        }
      }
    ]
  },
  {
    "id": 3,
    "instances": [
      {
        "id": 3,
        "owner": {
          "id": 1
        }
      }
    ]
  }
]

This is the operation I'm trying to execute

db.collection.update({},
{
  "$pull": {
    "instances": {
      "owner.id": 1
    }
  }
})

This version does not update anything.

ALTHOUGH, if I modify the filter to specify an id :

db.collection.update({
  "id": 2
},
{
  "$pull": {
    "instances": {
      "owner.id": 1
    }
  }
})

It works just fine on the document that has the id "2". Why can't I specify an empty filter ?

CodePudding user response:

You can use {multi: true} for this:

db.collection.update(
  {},
  {$pull: {instances: {"owner.id": 1}},
  {multi: true}
)

See how it works on the playground example

  • Related