为什么只有在集合不存在时,MongoDB才会更慢地插入记录?

bug*_*s94 7 javascript mongodb node.js

我正在进行MongoDB 3.2.17的基准测试以获得乐趣,并且无法理解这种行为的原因.

  • 当我在插入之前创建一个空集合时

    MongoDB x 906 ops/sec±2.78%(75次运行采样)

  • 当我不创建任何空集合,只是简单地运行 insertMany

    MongoDB x 87.81 ops/sec±94.31%(71次采样)// 错误率很高,为什么?

我的代码使用Benchmark.js,以便您可以指出我是否在那里犯了一些错误

var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
const MongoClient = require('mongodb').MongoClient;
var collectionMongodb = 'testrecords2';
Promise.all([
    MongoClient.connect('mongodb://localhost:27017/testme') 
]).then((clients) => {
    var nativeCollection = clients[0].db('testmongodb').collection(collectionMongodb)
    var records = [];
    for (var i = 0; i < 100; i++) {
        records.push({
            name: 'bugwheels' + i,
            interest: 'Not Many',
            job: 'Useless'
        })
    }
    suite
    .add('MongoDB', {
        defer: true,
        fn: function(def) {
            nativeCollection.insertMany(records, (e, r) => {
                def.resolve();
                // console.log(r)
            })
        }
    })
    .on('cycle', function(event) {
        console.log(String(event.target));
    })
    .on('complete', function() {
        console.log('Fastest is ' + this.filter('fastest').map('name'));
//          nativeCollection.drop()
    })
    .run({ 'async': true });    
})
Run Code Online (Sandbox Code Playgroud)

请让我知道出了什么问题?

我的StorageEngine

{
    "name" : "wiredTiger",
    "supportsCommittedReads" : true,
    "persistent" : true
 }
Run Code Online (Sandbox Code Playgroud)

我使用以下命令启动了mongoDB:

mongod --dbpath ./db
Run Code Online (Sandbox Code Playgroud)

Asy*_*sky 3

这很简单。您在每次运行中插入相同的 100 条记录。

当您在每次运行之间删除集合时,您正在测量删除集合然后向其中插入 100 个文档所需的时间。

当您注释掉删除集合时,您会在第一次运行中插入 100 条记录,但后续运行每次都会尝试将完全相同的 100 条文档插入到同一个集合中,并且它们都会收到错误:

exception: E11000 duplicate key error collection: testmongodb.testrecords2 index: _id_ dup key: { : ObjectId('5aa19388df671d3a065076f5') } code:DuplicateKey
Run Code Online (Sandbox Code Playgroud)

我认为您创建空集合的方式实际上会导致工作量发生显着变化,因此您应该做的一件事是通过每次生成唯一记录来确保正确进行基准测试。