- Install MongoDB >
- Generate Test Data
Generate Test Data¶
On this page
This tutorial describes how to quickly generate test data as needed to test basic MongoDB operations.
Insert Multiple Documents Using a For Loop¶
Iterate through the cursor.¶
The find()
method returns a cursor. To
iterate the cursor and return more
documents, type it
in the mongo
shell. The shell will
exhaust the cursor and return these documents:
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:
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:
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.
Example
Specify database name, collection name, and the number of
documents to insert as arguments to insertData()
.
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.