受欢迎的博客标签

MongoDB C# driver 2.x InsertManyAsync same as BulkWriteAsync

Published
I have to insert many documents in a MongoDB collection, using the new C# 2.0 driver. Is using either collection.InsertManyAsync(...) 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?   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. db.collection.initializeOrderedBulkOp() or thedb.collection.initializeUnorderedBulkOp()  https://docs.mongodb.org/manual/reference/method/db.collection.initializeUnorderedBulkOp/#db.collection.initializeUnorderedBulkOp Order of Operation With an unordered operations list, MongoDB can execute in parallel the write operations in the list and in any order. If the order of operations matter, use db.collection.initializeOrderedBulkOp() instead. Execution of Operations When executing an unordered list of operations, MongoDB groups the operations. With an unordered bulk operation, the operations in the list may be reordered to increase performance. As such, applications should not depend on the ordering when performing unordered bulk operations. Each group of operations can have at most 1000 operations. If a group exceeds this limit, MongoDB will divide the group into smaller groups of 1000 or less. For example, if the bulk operations list consists of 2000 insert operations, MongoDB creates 2 groups, each with 1000 operations. The sizes and grouping mechanics are internal performance details and are subject to change in future versions. To see how the operations are grouped for a bulk operation execution, call Bulk.getOperations() afterthe execution. Error Handling If an error occurs during the processing of one of the write operations, MongoDB will continue to process remaining write operations in the list. Example The following initializes a Bulk() operations builder and adds a series of insert operations to add multiple documents: var bulk = db.users.initializeUnorderedBulkOp(); bulk.insert( { user: "abc123", status: "A", points: 0 } ); bulk.insert( { user: "ijk123", status: "A", points: 0 } ); bulk.insert( { user: "mop123", status: "P", points: 0 } ); bulk.execute(); .