python - 如何使用 PyMongo 在重复键错误后继续插入

标签 python mongodb mongodb-query pymongo

如果我需要在MongoDB中插入一个尚不存在的文档

db_stock.update_one(document, {'$set': document}, upsert=True)

.将完成这项工作(如果我错了,请随时纠正我)

但是,如果我有一个文档列表并且想要将它们全部插入,那么最好的方法是什么?

这个 question 有一个单记录版本但我需要它的整体版本,所以它是不同的。

让我重新提出我的问题。我有数以百万计的文档,其中很少有可以存储的。如何在几秒钟内而不是几分钟/几小时内将剩余的存储在 MongoDB 中?

最佳答案

您需要使用 insert_many方法并将有序选项设置为 False

db_stock.insert_many(<list of documents>)

ordered 选项文档中所述:

ordered (optional): If True (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If False, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted.

这意味着即使存在重复键错误,插入也会继续。

演示:

>>> c.insert_many([{'_id': 2}, {'_id': 3}])
<pymongo.results.InsertManyResult object at 0x7f5ca669ef30>
>>> list(c.find())
[{'_id': 2}, {'_id': 3}]
>>> try:
...     c.insert_many([{'_id': 2}, {'_id': 3}, {'_id': 4}, {'_id': 5}], ordered=False)
... except pymongo.errors.BulkWriteError:
...     list(c.find())
... 
[{'_id': 2}, {'_id': 3}, {'_id': 4}, {'_id': 5}]

如您所见,_id 为 4、5 的文档被插入到集合中。


值得注意的是,这也可以在 shell 中使用 insertMany方法。您只需将未记录的选项 ordered 设置为 false

db.collection.insertMany(
    [ 
        { '_id': 2 }, 
        { '_id': 3 },
        { '_id': 4 }, 
        { '_id': 5 }
    ],
    { 'ordered': false }
)

关于python - 如何使用 PyMongo 在重复键错误后继续插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36083247/

相关文章:

python - 如何在 Pandas read_csv 函数中过滤加载行?

mongodb - 在 mongodb 中使用聚合请求按日期排序

mongodb count 每个字段/键的不同值的数量

Javascript/Node.js "Function name"不是一个函数

c++ - MongoDB C++:mongocxx::pool 线程安全吗?

java - 如何从 mongoDB 数组中返回匹配的元素

python - Django 查询集,小于或大于版本号

python - "Can only join an iterable" python 错误

python - 我的 Django 网址有什么问题?

node.js - MongoDB 按字段返回所有文档而不重复?