pythonmongodbflaskpymongoflask-pymongo

How to pull a nested Document


Referring to this Question, Now I want to remove dinner from Random Name 2, how can I do that: Here's what i tried:

din_val = data[0]
condition = {
    "username" : session['user']["username"],
    f"likings.{din_val}" : {
        "$exists" : True
    }
}
update_value = {
    "$pull" : {
        f"likings.$" : din_val
    }
}
response = mongo.db.appname.update(condition, update_value)

But the error I am receiving is
pymongo.errors.WriteError: Cannot apply $pull to a non-array value, full error: {'index': 0, 'code': 2, 'errmsg': 'Cannot apply $pull to a non-array value'}


Solution

  • Demo - https://mongoplayground.net/p/uYexli31rsc

    https://docs.mongodb.com/manual/reference/operator/update/pull/

    db.collection.update(
    { "name": "Random Name 2" },
    { $pull: { "likings": { dinner: { $exists: true } } }
    })