2012-09-30 163 views
1

作爲一部分for-in循環使用Python中pymongo我想添加一些嵌套的文件/一個linktype場是成爲links領域內的內部對象: 無論是links場或linktype字段在第一個這樣的條目被添加之前存在。

這是什麼命令?

這裏是添加鏈接前一個項目:

item = { 
    "_id" : ObjectId("5067c26b9d595266e25e825a"), 
    "name": "a Name" 
} 

並添加typeA類型的一個鏈接後:

toType = "typeA" 
to_link = {"_id" : ObjectId("5067c26b9d595266e25e825b"), "property":"value"} 

{ 
    "_id" : ObjectId("5067c26b9d595266e25e825a"), 
    "name": "a Name", 
    "links" : { 
     "typeA":{ 
      {"_id" : ObjectId("5067c26b9d595266e25e825b"), "property":"value"}  
     } 
    } 
} 

我曾嘗試:

db.collection.update({"name":"a Name"},{{"links":{"$addToSet":{toType:to_link}}}) 

它不工作。 如果我只是用:

db.collection.update({"name":"a Name"},{ {"$addToSet":{toType:to_link}}) 

的作品,但是這不是我想要的。

回答

1

$addToSet用於添加到數組。要將新屬性添加到您需要使用$set運營商和dot notation爲現有的嵌入式對象:

db.collection.update({name: 'a name'}, {$set: {'links.' + toType: to_link}}) 
+0

我才意識到我其實是想'typeA'是對象的數組。所以使用你的答案我已經意識到我正在尋找:'from_collection.update({「ID」:fromID},{「$ addToSet」:{'links。'+ toType:to_link}})'。儘管你已經回答了我的問題。 – johowie