PyMongo upsert 抛出“upsert 必须是 bool 的实例”错误
我正在通过 Python 对 MongoDB 运行更新。我有这一行:
self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True})
但它会抛出此错误:
raise TypeError("upsert must be an instance of bool")
但是 True
对我来说看起来像是 bool 的实例!
我应该如何正确编写此更新?
I'm running an update on my MongoDB from Python. I have this line:
self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True})
But it throws this error:
raise TypeError("upsert must be an instance of bool")
But True
looks like an instance of bool to me!
How should I correctly write this update?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PyMongo 的
update 的第三个参数()
是upsert
并且必须传递一个布尔值,而不是字典。将代码更改为:或将
upsert=True
作为关键字参数传递:您的错误可能是由于阅读 MongoDB 文档。 JavaScript 版本的
update
将一个对象作为其第三个参数,其中包含可选参数,例如upsert
和multi
。但由于 Python 允许将关键字参数传递给函数(与只有位置参数的 JavaScript 不同),这是不必要的,PyMongo 将这些选项作为可选函数参数。The third argument to PyMongo's
update()
isupsert
and must be passed a boolean, not a dictionary. Change your code to:Or pass
upsert=True
as a keyword argument:Your mistake was likely caused by reading about
update()
in the MongoDB docs. The JavaScript version ofupdate
takes an object as its third argument containing optional parameters likeupsert
andmulti
. But since Python allows passing keyword arguments to a function (unlike JavaScript which only has positional arguments), this is unnecessary and PyMongo takes these options as optional function parameters instead.根据 http://api.mongodb.org/python/ 2.3/api/pymongo/collection.html#pymongo.collection.Collection.update 你确实应该将 upsert 作为关键字传递,而不仅仅是 True,也就是说
Or
是比仅仅传递 True 更好的方法,就像你希望的那样如果不保留参数的顺序,传递其他 kwargs 例如
safe
或multi
代码可能会中断。According to http://api.mongodb.org/python/2.3/api/pymongo/collection.html#pymongo.collection.Collection.update you should indeed pass upsert as a keyword rather than just True, that is
Or
is a better approach than just passing True as if you ever wish to pass other kwargs such as
safe
ormulti
code might break if order of args is not kept.upsert 应该作为位置参数传递,就像这样
,或者作为关键字参数传递,就像这样
upsert should be passed as either positional parameter, like so
or as a keyword argument, like so