你需要使用insert_many http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_many方法并将有序选项设置为False
.
db_stock.insert_many(<list of documents>)
正如在ordered选项文档:
ordered(可选):如果为 True(默认),文档将按提供的顺序连续插入到服务器上。如果发生错误,所有剩余的插入都会中止。如果为 False,文档将以任意顺序(可能是并行)插入到服务器上,并且将尝试所有文档插入。
这意味着即使存在重复键错误,插入也会继续。
Demo:
>>> 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 https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/方法。您所需要的只是设置未记录的选项ordered
to false
.
db.collection.insertMany(
[
{ '_id': 2 },
{ '_id': 3 },
{ '_id': 4 },
{ '_id': 5 }
],
{ 'ordered': false }
)