PyMongo upsert 抛出“upsert 必须是布尔值”错误

79 投票
3 回答
59551 浏览
提问于 2025-04-16 12:09

我正在用Python对我的MongoDB进行更新。我有这一行代码:

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

但是它出现了这个错误:

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

可是我觉得True看起来像是布尔值的一个实例啊!

我应该怎么正确地写这个更新呢?

3 个回答

4

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

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

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

self.word_counts[source].update(
    {'date':posttime},
    {"$inc" : words},
    upsert=True)
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 更好,因为如果你以后想传递其他的参数,比如 safemulti,如果参数的顺序不对,代码可能会出错。

129

PyMongo的 update() 方法的第三个参数是 upsert,这个参数必须是布尔值(也就是True或False),而不是字典。你需要把你的代码改成:

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

或者你可以把 upsert=True 作为关键字参数传入:

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

你可能是因为查看了 MongoDB文档,才犯了这个错误。在JavaScript版本的 update 方法中,第三个参数是一个对象,可以包含像 upsertmulti 这样的可选参数。但在Python中,可以传递关键字参数给函数(而JavaScript只能传位置参数),所以在这里不需要这样做,PyMongo会把这些选项当作可选的函数参数来处理。

撰写回答