python - pymongo DuplicateKeyError - 在 upsert 期间

标签 python mongodb scrapy pymongo upsert

我注意到 pymongo 库有一个奇怪的行为。 当我从我的单元测试中运行以下代码时,一切正常(这 2 个文档存储在它们的集合中并且设置了 _id)。

property_db_item = {#"_id": str(bson.ObjectId()),"url": item['url'],
                            "price": item['price'],"rooms": item['rooms'],
                            "area": item['area'],"flor": item['flor'],
                            "street": item['street'],"city": item['city'],
                            "region": item['region'],"country": item['country'],
                            "photoUrls": item['photoUrls'],"updatedAt": str(date)}

        db.properties.update({"url": item['url']}, property_db_item, upsert=True)
        db.property_trends.update(
            {"url": item['url'], "date": date.strftime("%Y-%m")},
            {
                "$setOnInsert": {"url": item['url'], #"_id": str(bson.ObjectId())],
                                 "date": date.strftime("%Y-%m")},
                "$addToSet": {"prices": {date.strftime("%Y-%m-%d"): item['price']}}

            }, upsert=True)`

但是当我从终端执行它时(scrapy crawl myParser),并得到这个错误:

DuplicateKeyError(details["err"]) pymongo.errors.DuplicateKeyError: E11000 duplicate key error index: local.properties.$id dup key: { : null }

最佳答案

这是一个现有的 bug .更新到 local 数据库失败并显示 E11000 重复键错误索引:local.properties.$_id_ dup key: { : null }异常。

这是一个例子:

> use local
switched to db local
> db.properties.update({'url': 'test1'}, {'url2': 'test2'}, upsert=true)
> db.properties.update({'url': 'test1'}, {'url2': 'test2'}, upsert=true)
E11000 duplicate key error index: local.properties.$_id_  dup key: { : null }
> use local2
switched to db local2
> db.properties.update({'url': 'test1'}, {'url2': 'test2'}, upsert=true)
> db.properties.update({'url': 'test1'}, {'url2': 'test2'}, upsert=true)

关于python - pymongo DuplicateKeyError - 在 upsert 期间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16602542/

相关文章:

Python Selenium + Datepicker 问题

java - 具有 MongoDB Java 集合的动态 POJO 类型

python - 在 PyCharm python 控制台中复制 scrapy shell 功能

azure - Scrapyd 与 Windows 任务计划程序

python - pandas 使用 groupby 填充

python - 对自定义容器对象进行排序

javascript - Mongodb 聚合以对数组中最常见的项目进行排序?

mongodb - 用两个条件检查记录的最简单方法是什么,如果不存在则插入,如果存在一个或多个,则全部更新

python - 如何用Python绕过Incapsula

python - 导入错误: No module named pygtk