76

我正在从 Python 对我的 MongoDB 进行更新。我有这条线:

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

但它抛出了这个错误:

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

True对我来说看起来像是 bool 的一个实例!

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

4

3 回答 3

121

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将对象作为其第三个参数,其中包含可选参数,如upsertmulti。但是由于 Python 允许将关键字参数传递给函数(与 JavaScript 仅具有位置参数不同),因此这是不必要的,PyMongo 将这些选项作为可选的函数参数。

于 2011-02-20T07:39:07.680 回答
17

根据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 的顺序,代码可能会中断。

于 2012-10-23T11:02:50.240 回答
4

upsert 应该作为位置参数传递,就像这样

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

或作为关键字参数,像这样

self.word_counts[source].update(
    {'date':posttime},
    {"$inc" : words},
    upsert=True)
于 2014-02-09T16:34:48.360 回答