简体   繁体   中英

Pull from nested Array in MongoDB

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, aE:

{"$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.'}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM