Using MongoDB on Docker
Introduction
MongoDB is a widely popular NoSQL database today due to its simplicity and several advantages over relational databases. Through this guide, you'll learn how to quickly use MongoDB within Docker without going through many complex installation steps.
Note that before starting, you need to have Docker installed on your machine.
Starting MongoDB on Docker
You just need to execute the following command:
Explanation of the command:
- `-e MONGO_INITDB_ROOT_USERNAME=username -e MONGO_INITDB_ROOT_PASSWORD=password`: Sets environment variables for MongoDB initialization. You can replace "username" and "password" with your desired credentials.
- `--name mongo`: Sets the name for the container.
- `-p 27017:27017`: Exposes the MongoDB port for usage.
- `-v /data/db:/data/db`: Mounts a volume from the container to the host machine.
- `-d`: Starts the container in daemon mode.
- `mongo`: Specifies the image name, typically it would be mongo:latest.
After executing the command, if your machine doesn't have MongoDB installed, Docker will pull the mongo image to use. Subsequent executions will directly run the image.
Some MongoDB Queries
After successfully running MongoDB on Docker, let's try connecting to MongoDB and executing some simple commands as follows:
First, connect to MongoDB like this:
After that, you will be prompted to enter the password to continue.
Creating another account
Execute the following commands one by one:
User creation successful |
Inserting data into a collection
Execute the following commands to insert data into a collection. If the collection does not exist, it will be created:
Data insertion successful |
Connecting to MongoDB on NodeJS
I'll provide a straightforward demo using NodeJS and mongoose to connect to MongoDB like this:
Please like and share if you found this post helpful. Your support motivates me to create more valuable content!
Comments
Post a Comment