我正在通过 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 版本将对象作为其第三个参数,其中包含可选参数,例如 upsert
和 multi
。但是由于 Python 允许将关键字参数传递给函数(不像 JavaScript 仅具有位置参数),因此这是不必要的,PyMongo 将这些选项作为可选的函数参数。
关于python - PyMongo upsert 抛出 "upsert must be an instance of bool"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055797/