• MongoDB #$set的问题


    在 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 $set
    from pymongo import collection
    pymongo_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
  • 相关阅读:
    java作业5
    《大道至简》第五章读后感
    java作业4
    《大道至简》第四章读后感
    java作业3
    《大道至简》第三章读后感
    java作业2
    Java课程作业1
    《大道至简》第二章读后感
    《大道至简》第一章读后感
  • 原文地址:https://www.cnblogs.com/lwsup/p/7610920.html
Copyright © 2020-2023  润新知