MongoDB For Beginners(Using Docker)
Tags: mongodb, nosql, database, docker
Published: 2024-03-30 20:55:03

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](https://www.docker.com/get-started/) and just download according to you OS. 
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m03eza8igbve19y1lonu.png)

For confirmation go to terminal and type docker --version.
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7f96919mvatv67a0w9h.png)




---



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: {}
```


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

we can simply stop it using `Ctrl + c`
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfg581nxjmt5fqkpn09r.png)

And by using `docker compose down` will remove the containers from the docker.
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ykwghaa8xmc2dygy0jv.png)


Okey now we are going to connect again, by giving `docker compose up -d` 
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o26jsx8byloye97t49jq.png)


-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

0. 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`

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

2. Now we are going to connect the database. At first we are going to take the id using the docker ps commmand.
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v07wxhpf4bez3vdcptqz.png)

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


   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/blaoo4sopq9931n8w8s0.png)


---

29/3/24

####COLLECTIONS

Mongo stores documents(rows) in collections(tables)
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwa0u8i4hvpzufzcy1gl.png)

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



   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltc61iojndgd93m4b3e7.png)

**To see the collections** we can use,

             show collections;



   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3ezfzjy2rkswq2xvgiv.png)

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.


3. Here are some options of db.collection() , 
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8cngaai4mmgbrnbyzm5.png)

   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mfqpse8mwwdij0a6e9fs.png)

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



####DOCUMENTS


   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/na13iwnf1eto7cef6vep.png)


     
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7vhmlyw3syle6aqgbto.png)


1. Now we are going to create collections,

- `db.createCollections("person");`
- `db.createCollections("student");`

2. 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
}
```

we are going to paste it to our terminal and press **enter**,
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bq5o1xddapfay1gkjz41.png)

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


   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otduky4p34u8i3hs9e1o.png)



####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
    }
]
```

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



####USING FIND


   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/320ul3xrzldt32a99wjq.png)

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


2. Previous point we use only query, now we are going to use projections. 
    
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3d3tuhfkvlo9phryhjzk.png)

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


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

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



   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkipgcc7vo66ytgukfma.png)


####Incrementing Value

suppose we want to increment the value of total spent in book,
    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tuhba28zkzc2j1rwfx3n.png)

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

**Image-2**

   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p4ydyg7gxub25wktfhq4.png)

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

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



     
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fio2179hbrdhq7a9cffj.png)

    
   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pl7ws1i5ktf5r7s1joxf.png)


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


   ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kgj6mzrfncojiwax9v2f.png)


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




---

#THE END