2

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"

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

-1

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 }
    );

1 Comment

Your answer is not related to the question, and also it looks like the wrong query, it can not support $[] in the query part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.