2016-06-07 52 views
3

我在更新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,鍵是動態的。更新將需要在不同的深度。

+0

的[?如何將其插入後更新蒙戈文件(可能的複製http://stackoverflow.com/questions/4372797/how-do-i-update-a-mongo-document-after-inserted-it) – jano

+0

另一個答案:http://stackoverflow.com/questions/13710770/how-to-update-values-using -pymongo – jano

回答

1

首先,改變對象更新到這一點:

to_update = { 
    "house_no": "5102", 
    "street": "Some_street", 
    "city": "some_city", 
    "state": "some_state" 
} 

,然後用它來更新你想要的文件的特定部分:

collection.update_one({_id: id}, { '$set': {"details.address2" : to_update} }); 
0

使用這種添加地址2:

collection.update({ '_ ID':物件(DOC_ID)},{ '$設置': '細節%s' 的{% '地址2':ADDRES S2}},UPSERT = TRUE)

結帳完整代碼:

import pymongo 
from bson.objectid import ObjectId 

data = {"name": "Some_name", 
     "details": {"address1": {"house_no": "731", "street": "Some_street", "city": "some_city", "state": "some_state"}}} 

address2 = {"house_no": "731", "street": "Some_street", "city": "some_city", "state": "some_state"} 

connect = pymongo.MongoClient('192.168.4.202', 20020) 
database = connect['my_test'] 
collection = database['coll'] 

# # CREATE COLLECTIONS AND INSERT DATA 
# _id = collection.insert(data) 
# print _id 

doc_id = '57568aa11ec52522343ee695' 

collection.update({'_id': ObjectId(doc_id)}, {'$set': {'details.%s' % 'address2': address2}}, upsert=True) 
+0

當按鍵處於動態且深度不同時,它將不起作用。我已經更新了這個問題。 – Shipra

+0

@Shipra - 您的密鑰可以是動態的而不是「address2」變量使用任何密鑰名稱。如果你想要比使用'details。%s。%s。%s'%('var1','var2','var3')更深入。 –