zk-25
zk-25

Reputation: 23

mongodb $pull in array with another array

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"

Upvotes: 2

Views: 972

Answers (2)

Rafiq
Rafiq

Reputation: 11445

bellow quires worked for me well

let feed = await Feed.findOneAndUpdate(
      {
        _id: req.params.id,
        feeds: {
          $elemMatch: {
            type: FeedType.Post,
            locations: {
              $elemMatch: {
                uniqueName,
              },
            },
          },
        },
      },
      {
        $pull: {
          //@ts-ignore
          'feeds.$[].locations': { uniqueName },
        },
      },
      { new: true }
    );

or

let feed = await Feed.findOneAndUpdate(
      {
        $and: [
          {
            _id: req.params.id,
          },
          {
            'feeds.$[].locations': {
              $elemMatch: {
                uniqueName,
              },
            },
          },
        ],
      },
      {
        $pull: {
          //@ts-ignore
          'feeds.$[].locations': { uniqueName },
        },
      },
      { new: true }
    );

Upvotes: -1

turivishal
turivishal

Reputation: 36104

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

Upvotes: 2

Related Questions