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;

  function (err, connection) {
    var collection = connection.collection('customers');

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



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 live online training, plus books, videos, and digital content from nearly 200 publishers.