0

I have a document structure like this:

{
  "name": "Example",
  "description": "foo",
  "vocabulary": [
    ["apple", "pomme"],
    ["hello", "bonjour"],
    ["bus", "bus"]
  ]
}

Now I want to pull an array inside the vocabulary array by specifying the first item, a.E.:

{"$pull": {"vocabulary.$": ["apple"]}

Which should remove the array ["apple", "pomme"] from vocabulary, but this doesn't work.

I tried this ($pull from nested array), but it did not work, it threw

pymongo.errors.WriteError:
The positional operator did not find the match needed from the query., full error: {'index': 0, 'code': 2, 'errmsg': 'The positional operator did not find the match needed from the query.'}

1 Answer 1

0

Very tricky question.

I think for this case $ positional operator is not suitable.

Instead, you need an aggregation pipeline in update query. Query ($filter) the values with the "apple" word is not ($not) existed ($in) in the vocabulary array field. Then $set to the vocabulary field.

db.collection.update({},
[
  {
    "$set": {
      "vocabulary": {
        $filter: {
          input: "$vocabulary",
          cond: {
            $not: {
              $in: [
                "apple",
                "$$this"
              ]
            }
          }
        }
      }
    }
  }
])

Sample Mongo Playground

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

1 Comment

Thanks for the answer! Unfortunately, that doesn't work on my server, but it works in the playground, which is pretty odd...

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.