Home > Back-end >  replace nested document array mongodb with python
replace nested document array mongodb with python

Time:04-25

i have this document in mongodb

{
  "_id": {
    "$oid": "62644af0368cb0a46d7c2a95"
  },
  "insertionData": "23/04/2022 19:50:50",
  "ipfsMetadata": {
    "Name": "data.json",
    "Hash": "Qmb3FWgyJHzJA7WCBX1phgkV93GiEQ9UDWUYffDqUCbe7E",
    "Size": "431"
  },
  "metadata": {
    "sessionDate": "20220415 17:42:55",
    "dataSender": "user345",
    "data": {
      "height": "180",
      "weight": "80"
    },
    "addtionalInformation": [
      {
        "name": "poolsize",
        "value": "30m"
      },
      {
        "name": "swimStyle",
        "value": "mariposa"
      },
      {
        "name": "modality",
        "value": "swim"
      },
      {
        "name": "gender-title",
        "value": "schoolA"
      }
    ]
  },
  "fileId": {
    "$numberLong": "4"
  }
}

I want to update nested array document, for instance the name with gender-tittle. This have value schoolA and i want to change to adult like the body. I give the parameter number of fileId in the post request and in body i pass this

post request : localhost/sessionUpdate/4
and body:

{
    "name": "gender-title",
    "value": "adultos"
}

flask

@app.route('/sessionUpdate/<string:a>', methods=['PUT']) 
def sessionUpdate(a):
    datas=request.json
    r=str(datas['name'])
    r2=str(datas['value'])
    print(r,r2)
    r3=collection.update_one({'fileId':a, 'metadata.addtionalInformation':r}, {'$set':{'metadata.addtionalInformation.$.value':r2}})  
    return str(r3),200

i'm getting the 200 but the document don't update with the new value.

CodePudding user response:

As you are using positional operator $ to work with your array, make sure your select query is targeting array element. You can see in below query that it is targeting metadata.addtionalInformation array with the condition that name: "gender-title"

db.collection.update({
  "fileId": 4,
  "metadata.addtionalInformation.name": "gender-title"
},
{
  "$set": {
    "metadata.addtionalInformation.$.value": "junior"
  }
})

Here is the Mongo playground for your reference.

  • Related