How to Seed a MongoDB Database Using Docker Compose
Last Updated :
26 Apr, 2024
Seeding a MongoDB database is a common task in many development and testing scenarios. It involves populating the database with initial data to ensure consistent and predictable behavior during the application development and testing phases. Docker Compose is a powerful tool that simplifies the process of managing multi-container Docker applications, making it an excellent choice for seeding MongoDB databases in a containerized environment.
In this article, we'll explore how to seed a MongoDB database using Docker Compose, covering all the necessary concepts with beginner-friendly examples and outputs.
Why Seed a MongoDB Database?
Seeding a MongoDB database using Docker Compose offers several advantages:
- Automated Initialization: Docker Compose enables you to automate the database initialization process by defining seed data and executing it alongside other containerized services.
- Consistent Environments: With Docker Compose, you can ensure consistent database states across different environments (development, testing, production) by seeding data as part of your container setup.
- Version Control: Docker Compose configurations can be version-controlled alongside your application code, providing a clear history of database initialization procedures.
Using Docker Compose for Seeding MongoDB
Docker Compose is a tool for defining and running multi-container Docker applications. It uses YAML files to configure the services, networks, and volumes required for your application. By leveraging Docker Compose, we can easily set up a MongoDB container and seed it with initial data using a custom initialization script.
How to Seed a MongoDB Database Using Docker Compose
1. Create a Docker Compose File
Create a docker-compose.yml file in your project directory and define the MongoDB service along with its configuration. Additionally, specify a volume for persisting MongoDB data and mount a directory containing the seed data initialization script.
version: '3.8'
services:
mongodb:
image: mongo
ports:
- '27017:27017'
volumes:
- ./data:/data/db
- ./scripts:/docker-entrypoint-initdb.d
In this configuration:
- We define a MongoDB service named mongodb based on the official mongo Docker image.
- The MONGO_INITDB_DATABASE environment variable specifies the name of the database to create upon initialization.
- We map port 27017 on the host machine to the MongoDB container.
- We mount the mongo-seed directory from the host to /docker-entrypoint-initdb.d inside the container, where MongoDB looks for initialization scripts.
2. Create Seed Data Initialization Script
Create a JavaScript file named seed.js in the scripts directory. This script will be executed when the MongoDB container starts and will populate the database with seed data. Here's an example script to insert sample documents into a users collection:
// seed.js
db.users.insertMany([
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 35 },
{ name: 'Charlie', age: 25 }
]);
This script uses the insertMany method to seed the users collection with sample documents.
3. Start Docker Compose
Navigate to your project directory containing the docker-compose.yml file and run the following command to start Docker Compose:
docker-compose up -d
This command will create and start the MongoDB container in the background, mount the data and scripts directories, and execute the seed.js script to seed the database.
Docker Compose will:
- Download the MongoDB image if not already available.
- Create and start a container named my-mongodb based on the specified configuration.
- Mount the mongo-seed directory into the MongoDB container.
- Execute the seed.js script during MongoDB initialization.
4. Verify Seeding
Once the Docker Compose services are up and running, you can verify that the seeding process was successful by connecting to the MongoDB database and checking the seeded data.
Connect to MongoDB Container
Open a new terminal window and run the following command to connect to the MongoDB container:
docker exec -it my-mongodb mongo mydatabase
Verify Seeded Data
Once connected to the MongoDB shell, run the following commands to verify the seeded data
> use mydatabase
> db.users.find().pretty()
This will display the seeded users collection with the inserted documents
{ "_id" : ObjectId("60e26f48e5d856002e54713d"), "name" : "Alice", "email" : "[email protected]" }
{ "_id" : ObjectId("60e26f48e5d856002e54713e"), "name" : "Bob", "email" : "[email protected]" }
{ "_id" : ObjectId("60e26f48e5d856002e54713f"), "name" : "Charlie", "email" : "[email protected]" }
5. Stop and Remove Docker Containers
To stop the Docker Compose services and remove the containers, press Ctrl + C in the terminal where docker-compose up is running. Then, run the following command to clean up:
docker-compose down
Conclusion
Seeding a MongoDB database using Docker Compose is a straightforward process that offers numerous benefits for development and testing workflows. By leveraging Docker Compose, you can easily set up a MongoDB container and populate it with initial data using a custom initialization script.
This ensures consistent data across environments and enables developers and testers to work with realistic datasets during application development and testing. Experiment with the provided examples and explore additional customization options to suit your specific requirements.
Similar Reads
How to Connect to a MongoDB Database Using the Node.js Driver ?
MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON). In this article, we connect the MongoDB database to your b
4 min read
How to Connect to a MongoDB Database Using Node.js
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
4 min read
How to create new Mongodb database using Node.js ?
mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project. Please r
1 min read
How to drop database of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Connect Node to a MongoDB Database ?
Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
6 min read
How to drop all databases present in MongoDb using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
2 min read
How to Create a MongoDB Dump of Database?
MongoDB is a popular NoSQL database known for its flexibility, scalability, and ease of use. However, to protect our data from potential data loss or corruption, itâs critical to have a reliable MongoDB backup strategy in place. In this article, we will go through the process of creating a MongoDB d
7 min read
MongoDB - Create Database using Mongo Shell
MongoDB is a popular NoSQL database that uses collections and documents, which are highly flexible and scalable. Unlike relational databases (RDBMS), MongoDB does not use tables and rows but stores data in a more dynamic, JSON-like format. In this article, we'll explore how to create a MongoDB datab
4 min read
Create a database in MongoDB using Python
MongoDB is a general-purpose, document-based, distributed database built for modern application developers and the cloud. It is a document database, which means it stores data in JSON-like documents. This is an efficient way to think about data and is more expressive and powerful than the traditiona
2 min read
Docker - Setting up a MongoDB Container
MongoDB is a NoSQL database that is used in many web applications nowadays to store the data in the form of objects. Where on the other side docker is also getting so popular to launch the server fast and with using less space to launch it. So docker has created the MongoDB image to launch its conta
3 min read