DEV Community

chauhoangminhnguyen
chauhoangminhnguyen

Posted on • Updated on • Originally published at howtodevez.blogspot.com

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.

MongoDB Docker

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

If you found this content helpful, please visit the original article on my blog to support the author and explore more interesting content.

BlogspotDev.toFacebookX


Some series you might find interesting:

Top comments (0)