How to modify a field in a nested pymongo dictionary record in python

111 views Asked by At

I have a mongo db with following structure

{
"_id" : ObjectId("5f59c289fb28ab4476d4578b"),
"data" : [ 
    {
        "time" : "10-Sep-2020 11:33:22",
        "type" : "Med01",
        "id":123
        "expdate" : "01-Sep-2021",
        "in_stock" "Y"

    }, 
    {
        "time" : "10-Sep-2020 11:33:22",
        "type" : "Med06",
        "id":125
        "expdate" : "10-Sep-2020",
        "in_stock" "N"

    },
    {
        "time" : "10-Sep-2020 11:33:22",
        "type" : "LOC1",
        "id":103
        "expdate" : "10-Sep-2023",
        "in_stock" "Y"

    }
]

}

I would like to update the in_stock field based on the given id, say for example I need to modify the in_stock of medicine with id 103 to N

I tried with below and it is working but I won't be knowing the list number (2) in advance.

update_one({"_id": id_1}, {'$set': {"data.2.in_stock":'N'}})

I have the value 2 in a variable but not sure how to pass that in the above query. Can someone help?

1

There are 1 answers

0
Belly Buster On BEST ANSWER

You need to use the $ positional operator. Note this will match on the first matching array element only.

db.mycollection.update_one({'_id': id_1, 'data.id': 103}, {'$set': {"data.$.in_stock":'N'}})