dayuloli
dayuloli

Reputation: 17051

Most performant way to bulk insert in MongoDB

There are two ways to bulk insert documents in MongoDB:

  1. Passing in an array of documents to db.collection.insert, or
  2. Use Bulk.insert - available as of v2.6

Which one is more performant? I am assuming the latter is used as a convenience when combined with other write operations in a single block of Bulk Write Operations, and so the first is more performant. But has anyone done any tests or have logical or empirical proof on this?

Upvotes: 2

Views: 1018

Answers (1)

wdberkeley
wdberkeley

Reputation: 11671

At the mongo shell prompt, type

db.test.insert

You'll see the code for this function. If you read it, you'll see that passing in an array to insert and doing a bulk insert are the same thing. You need to look at the whole code, which is too lengthy to post here, to understand exactly what happens, but the key part is

var isMultiInsert = Array.isArray(obj);

if (isMultiInsert) {
    obj.forEach(function(doc) {
        bulk.insert(doc);
    });
}
else {
    bulk.insert(obj);
}

try {
    result = bulk.execute(wc);
    if (!isMultiInsert)
        result = result.toSingleResult();
}

This code is from the 2.6.7 mongo shell.

Upvotes: 5

Related Questions