Generate Test Data

This tutorial describes how to quickly generate test data as needed to test basic MongoDB operations.

Insert Multiple Documents Using a For Loop

Insert Multiple Documents with a mongo Shell Function

You can create a JavaScript function in your shell session to generate the above data. The insertData() JavaScript function that follows creates new data for use in testing or training by either creating a new collection or appending data to an existing collection:

function insertData(dbName, colName, num) {

  var col = db.getSiblingDB(dbName).getCollection(colName);

  for (i = 0; i < num; i++) {



The insertData() function takes three parameters: a database, a new or existing collection, and the number of documents to create. The function creates documents with an x field set to an incremented integer, as in the following example documents:

{ "_id" : ObjectId("51a4da9b292904caffcff6eb"), "x" : 0 }
{ "_id" : ObjectId("51a4da9b292904caffcff6ec"), "x" : 1 }
{ "_id" : ObjectId("51a4da9b292904caffcff6ed"), "x" : 2 }

Store the function in your .mongorc.js file. The mongo shell loads and parses the .mongorc.js file on startup so your function is available every time you start a session.


Specify database name, collection name, and the number of documents to insert as arguments to insertData().

insertData("test", "testData", 400)

This operation inserts 400 documents into the testData collection in the test database. If the collection and database do not exist, MongoDB creates them implicitly before inserting documents.