2013-02-17 102 views
8

多標誌我的工作pymongo,這是我的文檔:的Upsert和pymongo

{ 
    "_id": ObjectId("51211b57f07ddaa377000000"), 
    "assignments": { 
    "0": { 
     "0": { 
     "_id": ObjectId("5120dd7400a4453d58a0d0ec") 
     }, 
     "1": { 
     "_id": ObjectId("5120dd8e00a4453d58a0d0ed") 
     }, 
     "2": { 
     "_id": ObjectId("5120ddad00a4453d58a0d0ee") 
     } 
    } 
    }, 
    "password": "my_passwd", 
    "username": "john" 
} 

我想取消設置所有這些文檔的「分配」屬性。 我能夠這樣做,以實現這一在蒙戈外殼:

db.users.update({}, {$unset: {"assignments": 1}}, false, true) 

即,我通過UPSERT和多標誌作爲最後兩個參數對用戶收集的更新功能功能。 但是我這樣做與pymongo:

db.users.update({}, {"$unset": {"assignments": 1}}, False, True) 

但是Python解釋如下拋出一個錯誤:

File "notes/assignment.py", line 34, in <module> 
    db.users.update({}, {"$unset": {"assignments": 1}}, False, True) 
    File "/usr/local/lib/python2.7/dist-packages/pymongo/collection.py", line 481, in update 
    check_keys, self.__uuid_subtype), safe) 
    File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 852, in _send_message 
    rv = self.__check_response_to_last_error(response) 
    File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 795, in __check_response_to_last_error 
    raise OperationFailure(details["err"], details["code"]) 
pymongo.errors.OperationFailure: Modifiers and non-modifiers cannot be mixed 

我要去哪裏錯了?

+0

看看http://stackoverflow.com/questions/14443478/remove-subfields-from-mongodb-document也許你會發現一些熟悉的東西 – mderk 2013-02-17 20:19:37

回答

24

問題是您傳入的兩個標記不是upsertmulti。根據PyMongo的文檔Collection.update(找到here),看起來您可能會傳入upsertmanipulate選項的值,但我不確定。

你所要做的就是解決這個問題,就是使用Python最棒的特性之一:命名參數。通過指定您傳遞給update的哪些選項,除了確保這樣的事故不會發生之外,您還可以增加代碼的清晰度。

在這種情況下,我們想通過選項upsert=Falsemulti=True

db.users.update({}, { "$unset": { "assignments": 1 } }, upsert=False, multi=True) 
+0

哇!你太棒了,非常感謝你 – swaroopsm 2013-02-18 07:38:48