将嵌套文档数组 mongodb 替换为 python

replace nested document array mongodb with python

我在 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"
  }
}

我想更新嵌套数组文档,例如 gender-tittle 的名称。这有 schoolA 的价值,我想像 body 一样变成成人。我在 post 请求中给出了 fileId 的参数编号,在 body 中我传递了这个

post request : localhost/sessionUpdate/4
and body:

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

烧瓶

@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

我得到了 200,但文档没有更新为新值。

当您使用位置运算符 $ 处理数组时,请确保您的 select 查询以数组元素为目标。您可以在下面的查询中看到它以 metadata.addtionalInformation 数组为目标,条件是 name: "gender-title"

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

这里是Mongo playground供您参考。