Why is MongoDB much slower than inserts (with a unique index)?

I tested the limits of MongoDB to see if it would work for the upcoming project, and I noticed that upserts are pretty slow compared to inserts.

Of course, I would expect them to be slower, but not (almost) an order of magnitude slower (7400 versus 55000 op / sec). This uses the (desktop) code (nodejs native driver) that I used:

(async function() {

  let db = await require('mongodb').MongoClient.connect('mongodb://localhost:27017/mongo-benchmark-8764824692947');
  db.collection('text').createIndex({text:1},{unique:true})

  let batch = db.collection('text').initializeOrderedBulkOp();
  let totalOpCount = 0;
  let batchOpCount = 0;
  let start = Date.now();
  while(1) {

    totalOpCount++;
    batchOpCount++;
    if(batchOpCount === 1000) { // batch 1000 ops at a time
      await batch.execute();
      batch = db.collection('text').initializeOrderedBulkOp();
      batchOpCount = 0;
      let secondsElapsed = (Date.now() - start)/1000;
      console.log(`(${Math.round(totalOpCount/secondsElapsed)} ops per sec) (${totalOpCount} total ops)`)
    }

    /////////  INSERT TEST  ///////// (~55000 ops/sec)
    // batch.insert({text:totalOpCount});

    /////////  UPSERT TEST  ///////// (~7400 ops/sec)
    let text = Math.floor(Math.random()*1000000);
    batch.find({text}).upsert().updateOne({$setOnInsert:{text}});

    if(totalOpCount > 500000) {
      console.log("<< finished >>");
      await db.dropCollection('text');
      db.close();
      break;
    }

  }

})();

You can easily run it yourself by inserting it in index.js, running npm init -yand npm install --save mongodb, and thennode .

upsert , mongo , , . , , insert ? !

: $setOnInsert , .

+4
1

, if(batchOpCount === 1000) if(batchOpCount === 50000) ~ 90000 ops/sec insert ~ 35000 ops/sec upsert. , . , / ( ), , upserts , inserts, , , .

() 3- , , , , , upserts , , , (- ). -, , - .

0

Source: https://habr.com/ru/post/1674270/


All Articles