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:

docker run -e MONGO_INITDB_ROOT_USERNAME=username -e MONGO_INITDB_ROOT_PASSWORD=password --name mongo -p 27017:27017 -v /data/db:/data/db -d mongo

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:

docker exec -it mongo mongosh "mongodb://127.0.0.1:27017" --username username

After that, you will be prompted to enter the password to continue.


Creating another account

Execute the following commands one by one:

use admin -- switch to db admin

-- create new user
db.createUser({
user: 'username2',
pwd: 'password2',
roles: [{
role: 'readWrite',
db: 'test2'
}]
})

show users -- list all users


User creation successful
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:

-- db.{collection name}.insertOne
db.tests.insertOne({
name: 'Alice',
age: 30,
});

db.tests.insertMany([
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 },
]);

-- list all document
db.test.find()

Data insertion successful
Data insertion successful

Connecting to MongoDB on NodeJS

I'll provide a straightforward demo using NodeJS and mongoose to connect to MongoDB like this:

import mongoose, {Schema} from 'mongoose'

const host = 'mongodb://username:password@127.0.0.1:27017'
const conn = mongoose.createConnection(host)

const UserSchema = new Schema({
name: String,
age: Number,
email: String,
})

// create if not exist, map with `users` collection
const User = conn.model('user', UserSchema)
const newUser = new User({
name: 'name',
age: 20,
email: 'name@email.com',
})
await newUser.save()
const userData = await User.find()
console.log('Users', userData)


Please like and share if you found this post helpful. Your support motivates me to create more valuable content!

Comments

Popular posts from this blog

Kubernetes Practice Series

Docker Practice Series

NodeJS Practice Series

React Practice Series

Sitemap

Setting up Kubernetes Dashboard with Kind

Deploying a NodeJS Server on Google Kubernetes Engine

Create API Gateway with fast-gateway

Explaining Async/Await in JavaScript in 10 Minutes

A Handy Guide to Using Dynamic Import in JavaScript