17

I have to insert many documents in a MongoDB collection, using the new C# 2.0 driver. Is using either collection.InsertManyAsync(...) or collection.BulkWriteAsync(...) making any difference? (particularly about performance).

From what I understand from MongoDB documentation, an insert with an array of documents should be a bulk operation under the hood. Is that correct?

Thanks for your help.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Stefano Castriotta
  • 2,823
  • 3
  • 16
  • 26
  • Not sure about the answer but this might help: by MongoDB API description BulkWriteAsync - Performs multiple write operations. InsertManyAsync - Inserts many documents. – Ofir Oct 03 '15 at 10:35
  • 1
    If all you are doing is "insert" operations then there is effectively no difference. The point of difference is "BulkWrite" effectively allows mixed operations such as "insert", "update" and "remove" in the same batch. Please note that "under the hood", both are using the same Bulk Operations mechanism anyway. So your interpretation is correct. – Blakes Seven Oct 03 '15 at 10:38

1 Answers1

23

I found the answer looking at the driver source code: the InsertManyAsync uses internally the BulkWriteAsync.

So using InsertManyAsync it's the same as writing:

List<BsonDocument> documents = ...

collection.BulkWriteAsync(documents.Select(d => new InsertOneModel<BsonDocument>(d)));

Obviously, if all operations are Inserts, the InsertManyAsync should be used.

Manuel Jordan
  • 15,253
  • 21
  • 95
  • 158
Stefano Castriotta
  • 2,823
  • 3
  • 16
  • 26