Working with indexes

Like other databases, MongoDB needs to index data sets if we want queries on large sets to perform well.

In order to experience this firsthand, let's write a script which inserts 200,000 documents instead of just 20:

'use strict';

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect(
  'mongodb://127.0.0.1:27017/accounting',
  function (err, connection) {
    var collection = connection.collection('customers');

    var doInsert = function (i) {
      if (i < 200000) {
        var value = Math.floor(Math.random() * 10);
        collection.insert(
          {'n': '#' + i, 'v': value},
          function (err, count) {
            doInsert(i + 1);
          });
      } else {
        connection.close();
      }
    };

    doInsert(0);

  });

Call this script insert.js and execute it running node insert.js

Get The Node Craftsman Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.