简体   繁体   English

为什么人们应该使用单一插入方法而不是批量插入方法?

[英]Why should people ever use a single insertion method over a bulk insertion method?

I'm working with a MongoDB database for a project, and I'm making some abstractions for interacting with it.我正在为一个项目使用 MongoDB 数据库,并且正在为与之交互做一些抽象。 MongoDB exposes the following methods for collections: MongoDB 为 collections 公开了以下方法:

In terms of implementation, it's my understanding that the insertMany operation outperforms the inertOne operation, so the former section of code is prefered over the latter:在实现方面,我的理解是insertMany操作优于inertOne操作,因此前一段代码优于后者:

entries: list[object] = ...

# slower implementation
for entry in entries:
  collection.insert_one(entry)

# faster implementation
collection.insert_many(entries)

I've been writing some wrapping interfaces, though they're basically just a few lines in addition to the code above, so I'll leave those details out.我一直在编写一些包装接口,尽管它们基本上只是上面代码之外的几行,所以我将省略这些细节。 But here, my question is, outside of coding conventions and readability, do I have any incentive to use the single insertion interface if I can just do the following?但是在这里,我的问题是,除了编码约定和可读性之外,如果我可以执行以下操作,我是否有任何动机使用单一插入接口?

# put a single entry into a list and add it to the collection using the batch method
collection.insert_many([entry])

insertOne is marginally faster than insertMany at inserting a single document (in my very limit testing around 4-5% faster) - so in the case where you're inserting exactly one document, you should use insertOne - in the case where you're inserting many documents, you should use insertMany . insertOne在插入单个文档时比insertMany快(在我的极限测试中快 4-5%)——所以如果你正好插入一个文档,你应该使用insertOne如果你是插入很多文件,你应该使用insertMany

A second consideration is that insertMany will succeed or fail atomically - in most situations this is probably desirable, but if (for whatever reason) you expect some of your inserts to fail, but still want the rest to succeed, you'd want to use insertOne in a loop, with a try/catch.第二个考虑因素是insertMany将自动成功或失败 - 在大多数情况下这可能是可取的,但是如果(无论出于何种原因)您希望某些插入失败,但仍然希望 rest 成功,您会想要使用循环中的insertOne ,带有 try/catch。

^^ I now realise this portion of the answer was incorrect. ^^ 我现在意识到这部分答案是不正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM