how to work with nested objects in mongodb with python

Viewed 651
{
    "_id": 4545,
    "username": "testt",
    "data": {
        "passwords": [
            {
                "dataID": "175",
                "username": "enc_data",
                "password": "enc_data",
                "any": "enc_data",
                "any1": "enc_data",
                "any3": "enc_data"
            }
        ],
        "fav_list": []
    }
};

so I'm working on a project when I'll store the user encrypted data in a array inside of an object called 'data' so Ican have a nice organized data storing system but the problem here I can't really access the data from that nested object and I want to access the data with the 'dataID' and update it using the same id for each array object... I'm using python btw. thanks for reading.

2 Answers

The Mongo way of doing this is using arrayFilters, this let's you update an array element by using a query, like so:

db.collection.updateMany(
{},
{
  "$set": {
    "data.passwords.$[element].property_to_set": "new property value"
  }
},
{
  arrayFilters: [
    {
      "element.dataID": dataID
    }
  ],
})

Mongo Playground

And with pymongo:

collection.update_many(
{},
{
  "$set": {
    "data.passwords.$[element].property_to_set": "new property value"
  }
},
"array_filters"=[{"element.dataID": dataID}]
)

I removeed the [] of the passwords

data1={
    "_id": 4545,
    "username": "testt",
    "data": {
        "passwords": {
            "dataID": "175",
            "username": "enc_data",
            "password": "enc_data",
            "any": "enc_data",
            "any1": "enc_data",
            "any3": "enc_data"
        },
        "fav_list": []
    }
}
res=data1['data']['passwords']['dataID']
print(res)
# 175

# modify existing data
res=data1['data']['passwords']['dataID']=200
print(res)
# 200

# insert new key
res=data1['data']['passwords']['new_var']=6
print(data1['data']['passwords'].keys())
# dict_keys(['dataID', 'username', 'password', 'any', 'any1', 'any3', 'new_var'])



Related