Using MongoDB on Docker
Tags: docker, beginners, mongodb, node
Published: 2024-07-15 03:00:00

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qsbb74au1sja747z529t.png)

Starting MongoDB on Docker
--------------------------

You just need to execute the following command:
```sh
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:

```sh
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:

```sql
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jb6hdgmt5zly5pn21pqe.png)

### 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:

```sql
-- 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gbu36tz0wdp42xvu1pqz.png)

### Connecting to MongoDB on NodeJS

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

```ts
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!_**

**_If you found this content helpful, please visit [the original article on my blog](https://howtodevez.blogspot.com/2024/04/using-mongodb-on-docker.html) to support the author and explore more interesting content._**

<a href="https://howtodevez.blogspot.com/2024/03/sitemap.html" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Blogger-FF5722?style=for-the-badge&logo=blogger&logoColor=white" width="36" height="36" alt="Blogspot" /></a><a href="https://dev.to/chauhoangminhnguyen" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/dev.to-0A0A0A?style=for-the-badge&logo=dev.to&logoColor=white" width="36" height="36" alt="Dev.to" /></a><a href="https://www.facebook.com/profile.php?id=61557154776384" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/Facebook-1877F2?style=for-the-badge&logo=facebook&logoColor=white" width="36" height="36" alt="Facebook" /></a><a href="https://x.com/DavidNguyenSE" target="_blank" rel="noreferrer"><img src="https://img.shields.io/badge/X-000000?style=for-the-badge&logo=x&logoColor=white" width="36" height="36" alt="X" /></a>