DEV Community

Cover image for MongoDB For Beginners(Using Docker)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

MongoDB For Beginners(Using Docker)

25/3/24

Introduction

In this post we are going to learn basics of MongoDB. Creating documents, updating them and delete the data and all. It will be an awesome journey.

Prerequisite

  1. Docker
  2. WSL

Docker Installation

We can download MongoDB directly from the website but here we are going to use docker where we will have 2 containers. One is for MongoDB and the other one is for MongoExpress. To install docker please go to this link Official Docker and just download according to you OS.

Image description

For confirmation go to terminal and type docker --version.
Image description


26/3/24

Docker-Compose

Now we are going to create a docker-compose.yaml file. I created it in /d/BackendDevelopment/MongoDB , in this folder.

version: '3.8'

services:
  mongodb:
    image: mongo
    container_name: mongodb
    ports:
      - "27017:27017"
    volumes:
      - mongodb-data:/data
    environment:
      - MONGO_INITDB_ROOT_USERNAME=rootuser
      - MONGO_INITDB_ROOT_PASSWORD=rootpass

  mongo-express:
    image: mongo-express
    container_name: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongodb
      - ME_CONFIG_BASICAUTH_USERNAME=rootuser
      - ME_CONFIG_BASICAUTH_PASSWORD=rootpass
networks:
  default:
    name: mongodb_network

volumes:
  data: {}
Enter fullscreen mode Exit fullscreen mode

Access the created docker containers

Now we are going to create docker-compose file inside docker. For that i am going to use git bash terminal. At first we are going into that file location, /d/BackendDevelopment/MongoDB. Now we are going to run, docker-compose -f docker-compose.yaml up

It will create the container.
Image description

we can simply stop it using Ctrl + c

Image description

And by using docker compose down will remove the containers from the docker.

Image description

Okey now we are going to connect again, by giving docker compose up -d

Image description

-d: This flag stands for "detached mode". When we run docker-compose up without -d, it starts the services in the foreground, and we will see logs from all the containers in our terminal. When we add -d, it starts the services in the background, and you won't see the logs unless you explicitly request them.


27/3/24

  1. If we use docker compose down, it will totally shut down the server. So instead we can use
    docker compose stop // it will stop the container for temporarily . To start it we can simply give
    docker compose start

  2. The docker ps command is used to list all the currently running Docker containers on your system. It provides information such as the container ID, the names of the containers, the image they were created from, the command running inside the container, the ports being exposed, and the uptime of the container.

Image description

  1. Now we are going to connect the database. At first we are going to take the id using the docker ps commmand.

Image description

After that we are going to give,
docker exec -it 641223693b83 bash , and we will enter to the container. Now we will give,
mongosh "mongodb://localhost:27017" -u rootuser -p rootpass

And we are successfully connected to our mongoshell.

Image description

Image description


29/3/24

COLLECTIONS

Mongo stores documents(rows) in collections(tables)

Image description

To create collections we can use,
db.createCollection(name, {size: ..., capped: ..., max: ...})

Image description

To see the collections we can use,

         show collections;
Enter fullscreen mode Exit fullscreen mode

Image description

  1. Now if we want to drop the collections we can simply use, db.person.drop() .

  2. To create collections with data,
    db.createCollection("person", {capped: true, size: 6142800, max: 3000})

Here's what each option means:

capped: true: This option indicates that the collection being created is a capped collection. A capped collection has a fixed size and follows a FIFO (first-in-first-out) storage mechanism. Once the collection reaches its maximum size, it behaves like a circular buffer, overwriting older documents with new ones.

size: 6142800: This option specifies the maximum size, in bytes, that the capped collection can reach. In this case, the size is set to 6142800 bytes, which is approximately 6 MB.

max: 3000: This option sets the maximum number of documents that the capped collection can hold. Once the number of documents in the collection reaches this limit, older documents will be removed as new ones are added to maintain the capped collection's size.

  1. Here are some options of db.collection() ,

Image description

Image description

we now drop the collections again using , db.person.drop();

DOCUMENTS

Image description

Image description

  1. Now we are going to create collections,
  • db.createCollections("person");
  • db.createCollections("student");
  1. Another way we can create collections using, db.student.insert(student).

But the collection does not exist then it will create. Here is the full procedure,

  • At first we are going to copy the student data that we are going to insert to database. So, here is our student data,
student = {
    "firstName": "Retha",
    "LastName": "Killen",
    "email": "ekillean0@mysql.com",
    "gender": "F",
    "country": "Philippines",
    "isStudentActive": false,
    "facouriteSubjects": [
        "maths",
        "english",
        "it"
    ],
    "totalSpentInBooks": 0.00
}
Enter fullscreen mode Exit fullscreen mode

we are going to paste it to our terminal and press enter,

Image description

This will give us the JSON type data to BSON type data.

  • next we give the command, db.student.insert(student) , it will insert the data. For check we can give db.student.count().

Image description

Image description

INSERT DOCUMENTS

db.studnet.insertMany(students);

Now we will insert 11 student data as an array,

students = [
    {
        "firstName": "Alice",
        "lastName": "Johnson",
        "email": "alice.johnson@example.com",
        "gender": "F",
        "country": "United States",
        "isStudentActive": true,
        "favoriteSubjects": ["math", "science", "english"],
        "totalSpentInBooks": 75.50
    },
    {
        "firstName": "Bob",
        "lastName": "Smith",
        "email": "bob.smith@example.com",
        "gender": "M",
        "country": "Canada",
        "isStudentActive": false,
        "favoriteSubjects": ["history", "geography", "art"],
        "totalSpentInBooks": 120.25
    },
    {
        "firstName": "Catherine",
        "lastName": "Brown",
        "email": "catherine.brown@example.com",
        "gender": "F",
        "country": "United Kingdom",
        "isStudentActive": true,
        "favoriteSubjects": ["biology", "chemistry", "physics"],
        "totalSpentInBooks": 90.75
    },
    {
        "firstName": "David",
        "lastName": "Miller",
        "email": "david.miller@example.com",
        "gender": "M",
        "country": "Australia",
        "isStudentActive": true,
        "favoriteSubjects": ["computer science", "math", "music"],
        "totalSpentInBooks": 65.00
    },
    {
        "firstName": "Emily",
        "lastName": "Wilson",
        "email": "emily.wilson@example.com",
        "gender": "F",
        "country": "New Zealand",
        "isStudentActive": false,
        "favoriteSubjects": ["art", "english literature", "history"],
        "totalSpentInBooks": 80.50
    },
    {
        "firstName": "Frank",
        "lastName": "Garcia",
        "email": "frank.garcia@example.com",
        "gender": "M",
        "country": "Spain",
        "isStudentActive": true,
        "favoriteSubjects": ["math", "chemistry", "biology"],
        "totalSpentInBooks": 110.25
    },
    {
        "firstName": "Grace",
        "lastName": "Robinson",
        "email": "grace.robinson@example.com",
        "gender": "F",
        "country": "Germany",
        "isStudentActive": false,
        "favoriteSubjects": ["physics", "math", "computer science"],
        "totalSpentInBooks": 95.75
    },
    {
        "firstName": "Henry",
        "lastName": "Martinez",
        "email": "henry.martinez@example.com",
        "gender": "M",
        "country": "Mexico",
        "isStudentActive": true,
        "favoriteSubjects": ["english", "history", "geography"],
        "totalSpentInBooks": 70.00
    },
    {
        "firstName": "Isabella",
        "lastName": "Lee",
        "email": "isabella.lee@example.com",
        "gender": "F",
        "country": "China",
        "isStudentActive": false,
        "favoriteSubjects": ["music", "art", "math"],
        "totalSpentInBooks": 85.50
    },
    {
        "firstName": "James",
        "lastName": "Nguyen",
        "email": "james.nguyen@example.com",
        "gender": "M",
        "country": "Vietnam",
        "isStudentActive": true,
        "favoriteSubjects": ["chemistry", "biology", "physics"],
        "totalSpentInBooks": 100.25
    },
    {
        "firstName": "Kate",
        "lastName": "Wang",
        "email": "kate.wang@example.com",
        "gender": "F",
        "country": "Japan",
        "isStudentActive": false,
        "favoriteSubjects": ["english", "math", "computer science"],
        "totalSpentInBooks": 120.75
    }
]
Enter fullscreen mode Exit fullscreen mode

this is our data and we are going to copy it and paste it to our terminal and press enter . and type,

db.student.insertMany(students);

this insertMany will add multiple data to the collection.

Image description

USING FIND

Image description

find has 2 part, first one is the criteria and the second one is projection.


30/3/24

Today will continue from find.

  1. We can find user data using query like, db.student.find({firstName: "Kate"});

Image description

  1. Previous point we use only query, now we are going to use projections.

Image description

db.student.find({firstName: "Kate"});

This command finds all documents in the student collection where the firstName field is equal to "Kate".
Output: It returns an array with one document containing Kate's information.
db.student.find({firstName: "Kate"}, {firstName: 1, lastName: 3});

This command finds documents where the firstName field is equal to "Kate" and projects only the firstName and lastName fields.
In MongoDB, the value 1 means to include the field in the projection.
The value 3 doesn't have any specific meaning in this context. MongoDB ignores it and includes the lastName field as requested.
Output: It returns an array with one document containing only the firstName and lastName fields.
db.student.find({firstName: "Kate"}, {firstName: 1, lastName: 10});

This command finds documents where the firstName field is equal to "Kate" and projects only the firstName and lastName fields.
The value 10 doesn't have any specific meaning in this context. MongoDB ignores it and includes the lastName field as requested.
Output: It returns an array with one document containing only the firstName and lastName fields.
db.student.find({firstName: "Kate"}, {firstName: 1, lastName: 0});

This command tries to project only the firstName field (1 means include) and exclude the lastName field (0 means exclude).
However, MongoDB doesn't allow excluding fields when including others, so it throws an error.
Output: It returns a MongoServerError indicating that exclusion on the lastName field in inclusion projection is not allowed.
db.student.find({firstName: "Kate"}, {firstName: 1, lastName: -1});

This command finds documents where the firstName field is equal to "Kate" and projects only the firstName and lastName fields.
The value -1 means to exclude the lastName field from the projection.
Output: It returns an array with one document containing only the firstName and lastName fields, with lastName excluded.

UPDATE DOCUMENT

we use update keyword for update and $set sign for set the value.
db.student.update({ _id: ObjectId('66082af69ddc2f918cdb83ba')}, {$set: {firstName: "Katelyn"}});

Image description

Get rid of property

suppose we want to remove lastName of Katelyyn, we can use $unset ,

db.student.update({firstName: "Katelyyn"}, {$unset: {lastName: 1}});

Image description

And to add the lastName again, we can use update,
db.student.update({firstName: "Katelyyn"}, {$set: {lastName: "Wang"}});

Image description

Incrementing Value

suppose we want to increment the value of total spent in book,

Image description

we select the first id where the spent money is 0. And we are going to increase the value to 99. By using ,
db.student.update({_id: ObjectId('6606f5080c0b21ad5ddb83b0')}, {$inc: {totalSpentInBooks: 99}});

But an interesting thing is if i miss spelled anything and press enter, it will show the query worked, i dont know why. Let me share 2 images,

Image-1

Image description

Image-2

Image description

In image 1 i misspelled in totalSpentInBooks, i wrote totatSpentInBooks. However, it shows the command worked but in the output we can see the price 99 is not increased.

On the other hand when we fix the spelling then it worked properly, we can see it in image 2.

And we can easily check it from modifiedCount value.

PULL & PUSH
we can use pull to remove something from our databse. like we want to remove math from this id,

Image description

db.student.update({_id: ObjectId('66082af69ddc2f918cdb83ba')}, {$pull: {favoriteSubjects: "math"}});

Image description

Image description

same way we can use push to insert the data.

db.student.update({_id: ObjectId('66082af69ddc2f918cdb83ba')}, {$push: {favoriteSubjects: 'math'}});

it will add the math to the favoriteSubjects.


DELETE DOCUMENTS

We can easily delete data using delete() function.

  1. We can use deleteOne() for only item delete
  2. db.student.deleteOne({_id: ObjectId('6606f5080c0b21ad5ddb83b0')}); this will delete the id data, if pass without query then it will delete 1 item from the beginning.

Image description

Image description

  1. For multiple item delete we can use deleteMany(). If we want to delete all the female data then we can simply give, db.student.deleteMany({gender: 'F'});

Image description


THE END

Top comments (4)

Collapse
 
rohiitbagal profile image
Rohit

Please can you tell what is difference between Atlas and docker....i don't know anything about docker can you tell me something about that .... where that is used...

Collapse
 
rifat87 profile image
Tahzib Mahmud Rifat

In simple words Docker is a platform for building, shipping, and running containerized applications, you watch this video,
Docker

Collapse
 
rifat87 profile image
Tahzib Mahmud Rifat

Though i don't know much , i am learning too

Collapse
 
rifat87 profile image
Tahzib Mahmud Rifat

Feel free to give feedbacks.