Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

Learn why MongoDB was selected as a leader in the 2024 Gartner® Magic Quadrant™
MongoDB Developer
MongoDB
plus
Sign in to follow topics
MongoDB Developer Center
chevron-right
Developer Topics
chevron-right
Products
chevron-right
MongoDB
chevron-right

How to Seed a MongoDB Database with Fake Data

Joe Karlsson2 min read • Published Jan 28, 2022 • Updated Sep 23, 2022
MongoDB
Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Have you ever worked on a MongoDB project and needed to seed your database with fake data in order to provide initial values for lookups, demo purposes, proof of concepts, etc.? I'm biased, but I've had to seed a MongoDB database countless times.
First of all, what is database seeding? Database seeding is the initial seeding of a database with data. Seeding a database is a process in which an initial set of data is provided to a database when it is being installed.
In this post, you will learn how to get a working seed script setup for MongoDB databases using Node.js and faker.js.

The Code

This example code uses a single collection of fake IoT data (that I used to model for my IoT Kitty Litter Box project). However, you can change the shape of your template document to fit the needs of your application. I am using faker.js to create the fake data. Please refer to the documentation if you want to make any changes. You can also adapt this script to seed data into multiple collections or databases, if needed.
I am saving my data into a MongoDB Atlas database. It's the easiest way to get a MongoDB database up and running. You'll need to get your MongoDB connection URI before you can run this script. For information on how to connect your application to MongoDB, check out the docs.
Alright, now that we have got the setup out of the way, let's jump into the code!
1/* mySeedScript.js */
2
3// require the necessary libraries
4const faker = require("faker");
5const MongoClient = require("mongodb").MongoClient;
6
7function randomIntFromInterval(min, max) { // min and max included
8 return Math.floor(Math.random() * (max - min + 1) + min);
9}
10
11async function seedDB() {
12 // Connection URL
13 const uri = "YOUR MONGODB ATLAS URI";
14
15 const client = new MongoClient(uri, {
16 useNewUrlParser: true,
17 // useUnifiedTopology: true,
18 });
19
20 try {
21 await client.connect();
22 console.log("Connected correctly to server");
23
24 const collection = client.db("iot").collection("kitty-litter-time-series");
25
26 // The drop() command destroys all data from a collection.
27 // Make sure you run it against proper database and collection.
28 collection.drop();
29
30 // make a bunch of time series data
31 let timeSeriesData = [];
32
33 for (let i = 0; i < 5000; i++) {
34 const firstName = faker.name.firstName();
35 const lastName = faker.name.lastName();
36 let newDay = {
37 timestamp_day: faker.date.past(),
38 cat: faker.random.word(),
39 owner: {
40 email: faker.internet.email(firstName, lastName),
41 firstName,
42 lastName,
43 },
44 events: [],
45 };
46
47 for (let j = 0; j < randomIntFromInterval(1, 6); j++) {
48 let newEvent = {
49 timestamp_event: faker.date.past(),
50 weight: randomIntFromInterval(14,16),
51 }
52 newDay.events.push(newEvent);
53 }
54 timeSeriesData.push(newDay);
55 }
56 collection.insertMany(timeSeriesData);
57
58 console.log("Database seeded! :)");
59 client.close();
60 } catch (err) {
61 console.log(err.stack);
62 }
63}
64
65seedDB();
After running the script above, be sure to check out your database to ensure that your data has been properly seeded. This is what my database looks after running the script above.
Screenshot showing the seeded data in a MongoDB Atlas cluster.
Once your fake seed data is in the MongoDB database, you're done! Congratulations!

Wrapping Up

There are lots of reasons you might want to seed your MongoDB database, and populating a MongoDB database can be easy and fun without requiring any fancy tools or frameworks. We have been able to automate this task by using MongoDB, faker.js, and Node.js. Give it a try and let me know how it works for you! Having issues with seeding your database? We'd love to connect with you. Join the conversation on the MongoDB Community Forums.

Facebook Icontwitter iconlinkedin icon
Rate this tutorial
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

Create a RESTful API With .NET Core and MongoDB


Sep 11, 2024 | 8 min read
Tutorial

Modernize Your Insurance Data Models With MongoDB Relational Migrator


Jun 03, 2024 | 14 min read
Quickstart

Introduction to MongoDB and Helidon


Nov 12, 2024 | 6 min read
Tutorial

Leveraging Atlas Vector Search With HashiCorp Terraform: Empowering Semantic Search in Modern Applications


May 02, 2024 | 4 min read
Table of Contents
  • The Code