如果我需要在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/