我正在从Python更新我的MongoDB。我有这样一句话:
self.word_counts[source].update({'date':posttime},{"$inc" : words},{'upsert':True})但是它抛出了这个错误:
raise TypeError("upsert must be an instance of bool")但在我看来,True就像是bool的一个实例!
我应该如何正确地编写此更新?
发布于 2011-02-20 15:39:08
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版本接受一个对象作为其第三个参数,其中包含upsert和multi等可选参数。但是,由于PyMongo允许将关键字参数传递给函数(与只有位置参数的JavaScript不同),这是不必要的,Python将这些选项作为可选函数参数。
发布于 2012-10-23 19:02:50
根据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更好的方法,因为如果您希望传递其他kwarg,例如safe或multi,如果不保持args的顺序,代码可能会崩溃。
发布于 2014-02-10 00:34:48
upsert应该作为位置参数传递,如下所示
self.word_counts[source].update(
{'date':posttime},
{"$inc" : words},
True)或者作为关键字参数,如下所示
self.word_counts[source].update(
{'date':posttime},
{"$inc" : words},
upsert=True)https://stackoverflow.com/questions/5055797
复制相似问题