Remove array element for filtered object

I currently have a query, that filters elements of array and sets a field value for them.

        Schedule.collection.updateMany(
            { },
            {
                $set: { 'objectName.$[elem].fieldName': 'value' }
            },
            {
                arrayFilters: [ <filters here>]
            }
        );

That works perfectly. But now I need just to remove that element at all. I’ve checked unset and pull options, but I probably don’t fully understand the way to use them. I’m looking for a change like

$set: { 'availability.$[elem].status': 'past' } -> $objectName: { 'availability.$[elem] }

Hi @Daria_N_A , and welcome to the forums!

$unset should work for this. I tried this very simple example, and it worked for me.

First, add some data to your collection:

db.schedule.insertOne({sports: [{name: "running", completed: true}, {name: "swimming", completed: false}]});

You should have an element that looks like this:

{
  "_id": {
    "$oid": "66c3313298a302c33b5c6922"
  },
  "sports": [
    {
      "name": "running",
      "completed": true
    },
    {
      "name": "swimming",
      "completed": false
    }
  ]
}

Then, use the $unset operator with the arrayFilters as you did:

db.schedule.updateMany(
  {}, 
  {$unset: {"sports.$[elem].completed": ""}}, 
  {arrayFilters: [ {"elem.completed": true} ]}
);

Your document should now look like this:

{
  "_id": {
    "$oid": "66c3313298a302c33b5c6922"
  },
  "sports": [
    {
      "name": "running"
    },
    {
      "name": "swimming",
      "completed": false
    }
  ]
}

I hope this helps!
-Joel

1 Like

Thanks! I haven’t tried this solution, got this one working instead of set (and array filters removed):

                $pull: {
                    objectName: {
                        rephrased filters here
                    }
                }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.