mongodb $pull in array with another array

Viewed 382

Help me please to remove elements in an array with such document schema:

contracts: [
    {
      bandwidth: {
        calculated: {
          value: Number,
          documents: [id1, id2, id3, id4],
        }
      }
    }
  ]

I want to delete elements in all documents array that are in filter array.

I tried:

const documentsToDelete = [id2, id3]

const points = await Point.updateMany({
        $pull: {
            contracts: {"bandwidth.calculated.documents": {$in: documentsToDelete}}
        },
      }); 

But it does not work. The resulting array must contain "id1" and "id4"

1 Answers

Correct the things,

  • the first parameter is the query part to match the condition
  • the contracts is an array so use $[] to update operation in all elements
const documentsToDelete = [id2, id3];
const points = await Point.updateMany(
  {},
  {
    $pull: {
      "contracts.$[].bandwidth.calculated.documents": {
        $in: documentsToDelete
      }
    }
  }
)

Playground

Related