標籤:欄位   引入   name   資料   rms   strong   查看   def   war   
在 MongoDB 2.4 及以前版本中, db.collections.update({…},{“$set”: {}}), 也即 “空 $set” 是可以正常執行的。配合 upsert 等參數執行時可以有不同的方便用法.
但是升級到 MongoDB 2.6 以後, 由於引入了嚴格的參數檢查, 試圖進行空 $set 操作時, 會出現下面這樣的錯誤。
> use test                               #建立資料庫switched to db test
> db.createCollection(‘lwslws‘)          #建立集合{ "ok" : 1 }> show collections                       #查看集合lwslws> db.lwslws.insert({‘name‘:‘lws‘})       #插入資料WriteResult({ "nInserted" : 1 })
> db.lwslws.find()                       #查看資料{ "_id" : ObjectId("59cdcce01b4793371a9bb3b0"), "name" : "lws" }
                                         #新增欄位> db.lwslws.update({"_id" : ObjectId("59cdcce01b4793371a9bb3b0")},{‘$set‘:{‘age‘:25}})         WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
                         #查看資料> db.lwslws.find(){ "_id" : ObjectId("59cdcce01b4793371a9bb3b0"), "name" : "lws", "age" : 25 }
                                          #更新資料,但是傳入空值。> db.lwslws.update({"_id" : ObjectId("59cdcce01b4793371a9bb3b0")},{‘$set‘:{}})WriteResult({    "nMatched" : 0,    "nUpserted" : 0,    "nModified" : 0,    "writeError" : {        "code" : 9,        "errmsg" : "‘$set‘ is empty. You must specify a field like so: {$set: {<field>: ...}}"    }})
# Monkey patch pymongo to allow empty $setfrom pymongo import collectionpymongo_collection_update = collection.Collection.update def pymongo_collection_update_with_empty_set_support(self, spec, document, *args, **kwargs):    if "$set" in document and document["$set"] == {}:        document.pop("$set")        if document == {}:            return None    return pymongo_collection_update(self, spec, document, *args, **kwargs) collection.Collection.update = pymongo_collection_update_with_empty_set_support
 
MongoDB #$set的問題