python - PyMongo upsert 抛出 "upsert must be an instance of bool"错误

标签 python mongodb pymongo

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

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

但是它会抛出这个错误:

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

但是 True 对我来说就像一个 bool 实例!

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

最佳答案

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

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 将这些选项作为可选的函数参数。

关于python - PyMongo upsert 抛出 "upsert must be an instance of bool"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055797/

相关文章:

c# - 如何制作 ObjectIds 的字符串表示而不必为每个成员指定它

python - pymongo中的多个查询

python - 从另一个 .ipynb 文件导入函数

python - 显示 : character in the timezone offset using datetime. strftime

python - GitPython 无法设置 git config 用户名和电子邮件

javascript - 在 mongodb 中用 mongoose 更新对象中的字段

python - 为什么 time.clock 给出的耗时比 time.time 长?

mysql - 如何基于Node.js为书店制作正确的BD

python - 通过 httpd 上的 Flask-PyMongo 连接到 MongoHQ URI 时出现 ConnectionFailure

python - 为 Python 3.3 安装分发版