【问题标题】:PyMongo upsert throws "upsert must be an instance of bool" errorPyMongo upsert 抛出“upsert 必须是 bool 的实例”错误
【发布时间】:2011-06-30 15:49:33
【问题描述】:

我正在通过 Python 在我的 MongoDB 上运行更新。我有这一行:

self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True})

但是它会抛出这个错误:

raise TypeError("upsert must be an instance of bool")

但是True 在我看来就像一个 bool 实例!

我应该如何正确编写此更新?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    PyMongo 的update() 的第三个参数是upsert,并且必须传递一个布尔值,而不是字典。将您的代码更改为:

    self.word_counts[source].update({'date':posttime}, {"$inc" : words}, True)
    

    或将upsert=True 作为关键字参数传递:

    self.word_counts[source].update({'date':posttime}, {"$inc" : words}, upsert=True)
    

    您的错误可能是由于阅读了MongoDB docs 中的update() 而造成的。 update 的 JavaScript 版本将对象作为其第三个参数,其中包含可选参数,例如 upsertmulti。但由于 Python 允许将关键字参数传递给函数(不像 JavaScript 仅具有位置参数),因此这是不必要的,PyMongo 将这些选项作为可选的函数参数。

    【讨论】:

    • 谢谢,显然我正在处理的示例不正确。
    • db..update( {}, {}, upsert=False) pymongo version = pymongo==3.11.0 这对我有用,试试 :)
    【解决方案2】:

    根据http://api.mongodb.org/python/2.3/api/pymongo/collection.html#pymongo.collection.Collection.update,您确实应该将 upsert 作为关键字传递,而不仅仅是 True,即

    self.word_counts[source].update({'date':posttime},{"$inc" : words},**{'upsert':True})
    

    或者

    self.word_counts[source].update({'date':posttime},{"$inc" : words},upsert=True)
    

    是一种比只传递 True 更好的方法,就像您希望传递其他 kwargs,例如 safemulti 如果不保留 args 的顺序,代码可能会中断。

    【讨论】:

      【解决方案3】:

      upsert 应该作为位置参数传递,就像这样

      self.word_counts[source].update(
          {'date':posttime},
          {"$inc" : words},
          True)
      

      或作为关键字参数,像这样

      self.word_counts[source].update(
          {'date':posttime},
          {"$inc" : words},
          upsert=True)
      

      【讨论】:

        猜你喜欢
        • 2021-06-20
        • 2013-05-04
        • 2021-03-03
        • 2018-03-12
        • 1970-01-01
        • 2016-09-22
        • 2021-01-26
        • 2017-03-20
        • 2021-02-13
        相关资源
        最近更新 更多