我正在从 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
并且必须传递一个布尔值,而不是字典。将您的代码更改为:
self.word_counts[source].update({'date':posttime}, {"$inc" : words}, True)
upsert=True
或作为关键字参数传递:
self.word_counts[source].update({'date':posttime}, {"$inc" : words}, upsert=True)
您的错误可能是由于阅读update()
了MongoDB 文档中的内容造成的。JavaScript 版本update
将对象作为其第三个参数,其中包含可选参数,如upsert
和multi
。但是由于 Python 允许将关键字参数传递给函数(与 JavaScript 仅具有位置参数不同),因此这是不必要的,PyMongo 将这些选项作为可选的函数参数。
根据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 一样,safe
或者multi
如果不保留 args 的顺序,代码可能会中断。
upsert 应该作为位置参数传递,就像这样
self.word_counts[source].update(
{'date':posttime},
{"$inc" : words},
True)
或作为关键字参数,像这样
self.word_counts[source].update(
{'date':posttime},
{"$inc" : words},
upsert=True)