我在更新mongo中的嵌套json結構時遇到困難。 我正在使用pymongo以及Mongoengine-Rest-framework。PyMongo:JSON密鑰在mongo中得到更新
由於這個特定的json具有動態結構並且嵌套很深,所以我選擇在mongo-engine ORM上使用pymongo。
創建,檢索和刪除操作運行良好。 我想就更新問題提出一些建議。
讓我們考慮一個樣品物體,其是在蒙戈已經存在:
st1 = {
"name": "Some_name",
"details": {
"address1": {
"house_no": "731",
"street": "Some_street",
"city": "some_city"
"state": "some_state"
}
}
}
如果我嘗試通過在所述更新命令_id是用於條件發送JSON ST2增加地址2的細節來更新ST1更新用,
st2 = {
"details": {
"address2": {
"house_no": "5102",
"street": "Some_street",
"city": "some_city"
"state": "some_state"
}
}
}
我得到以下對象ST3作爲結果,在蒙戈,
st3 = {
"name": "Some_name",
"details": {
"address2": {
"house_no": " 5102",
"street": "Some_street",
"city": "some_city"
"state": "some_state"
}
}
}
而不是預期的st4對象。
st4 = {
"name": "Some_name",
"details": {
"address1": {
"house_no": "731",
"street": "Some_street",
"city": "some_city"
"state": "some_state"
},
"address2": {
"house_no": "5102",
"street": "Some_street",
"city": "some_city"
"state": "some_state"
}
}
}
我更新的命令是:
result = collection.update_one({'_id': id}, doc)
其中
ID:文檔_id
DOC:(這裏)ST2
集合:pymongo colllection對象
原始的JSON深度是6,鍵是動態的。更新將需要在不同的深度。
的[?如何將其插入後更新蒙戈文件(可能的複製http://stackoverflow.com/questions/4372797/how-do-i-update-a-mongo-document-after-inserted-it) – jano
另一個答案:http://stackoverflow.com/questions/13710770/how-to-update-values-using -pymongo – jano