Everything you should know about MongoDB
Tags: mongodb, database, tutorial
Published: 2022-08-27 07:54:50


**Watch Full Course of MongoDB on YouTube**

{% embed https://youtu.be/9cWm74DteMQ %}


## MongoDB : Introduction

**MongoDB**, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). 

*MongoDB records are called documents and they look very much like objects as they use Key-pair. *

> A simple MongoDB document Structure:


```
{
‘title’:'MongoDb World',
‘rating’: 10,
‘duration’: 200
‘Youtube’: 'Bitfumes'
}
// It is much easy to work with this if you are using JavaScript because 
// documents are very much like JSON or JavaScript objects. 
// Secondly, it allows us to store nested documents within a document.
{
‘title’:'MongoDb World',
‘rating’: 9,
‘duration’: 400,
‘author’:{
  ‘firstname’:'…',
  ‘lastname’:'…'
}
}
```

**Q) Why MongoDB?**    
   ->  There are four major reasons:

**1. Flexibility:**
MongoDB uses documents that can contain sub-documents in complex hierarchies making it expressive and flexible. 

**2. Flexible Query Model:**
The user can selectively index some parts of each document or a query based on regular expressions, ranges, or attribute values, and have as many properties per object as needed by the application layer.

**3. Native Aggregation:**
Native aggregation allows users to extract and transform data from the database. The data can either be loaded into a new format or exported to other data sources. 

**4. Schema-less model:**
Applications get the power and responsibility to interpret different properties found in a collection's documents. 

### Feature Of MongoDB

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


**Q)But What is the difference between relational and Non-Relational Databases?**
 

![relation vs non.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661155959457/5L0AgHZ6J.png)



#### **Structural representation of MongoDB**

![collect.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661171969028/h6i6aZ9FG.png)

we have a **MongoDB** database now inside you can have one collection that collection can have a single document it can have more than two or three any number of documents. So collection to the document now you can also have more than one collection and similar to that we can have more than one document inside the collection so the hierarchy is something like database collection document and inside the document, we should have the fields.


```
{
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }
``` 

The above fields have the following data types:

1. **_id** holds an ObjectId(Which is Uniquely Generated by MongoDB).   
2. **name** holds an embedded document(document inside the document) that contains the fields first and last.
3. **birth** and **death** hold values of the Date type.
4. **contribs** holds an array of strings.
5. **views** holds a value of the NumberLong type.



![mongodb1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661158568415/wF6nH4Cc1.png)


**Let's see How to Install MongoDB on your machine**

Go to the Install section on the [MongoDB](https://www.mongodb.com/docs/manual/administration/install-community/) website.
use the brew to install the community edition but with the brew the community edition you also get the shell or I can call it mongoose but with windows installation, if you install this MongoDB service you can directly download this MongoDB MSI file and then open it and use the wizard to install it that's easy but you have to install the mongoose explicitly the thing which is going to help you to access the MongoDB from your shell from your command prompt.

Or you can watch [Installation Part Here](https://youtu.be/9cWm74DteMQ?t=494)

### Create a New Database and Collection
**[Watch here](https://youtu.be/9cWm74DteMQ?t=1413)**

To run commands in mongosh, you must first connect to a MongoDB deployment.

To display the database you are using, type **db** :

To switch databases, use <db> helper, as in the following example:


```
use <Database_Name>

``` 

To create a new database, issue the use <db> command with the database that you would like to create. For example, the following commands create both the database myNewDatabase and the collection myCollection using the insertOne() operation:


```
use myNewDatabase
db.myCollection.insertOne( { x: 1 } );
``` 

> **If a collection does not exist, MongoDB creates the collection when you first store data for that collection.This is the special power of MongoDB**

![power.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1661164198870/9HcHVbVGW.webp)


#### How to Perform CRUD Operations in MongoDB

**Q) What is CRUD?**
  -> CRUD operation means creating, reading, updating, and deleting documents.
     
### **Insert Documents in MongoDB**
[Watch here](https://youtu.be/9cWm74DteMQ?t=2471)

**The MongoDB shell provides the following methods to insert documents into a collection:**

- To insert a single document, use **db.collection.insertOne()**.
- To insert multiple documents, use **db.collection.insertMany()**.

**If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document.**


```
//Example of InsertOne()

use sample_mflix
db.movies.insertOne(
  {
    title: "The Favourite",
    genres: [ "Drama", "History" ],
    year: 2018,
    directors: [ "Yorgos Lanthimos" ],
    type: "movie"
  }
)
```


```
//Example of insertMany()

use sample_mflix
db.movies.insertMany([
   {
      title: "Jurassic World: Fallen Kingdom",
      genres: [ "Action", "Sci-Fi" ],
      year: 2018,
      directors: [ "J. A. Bayona" ],
      type: "movie"
    },
    {
      title: "Titanic",
      genres: [ "Comedy", "Action" ],
      year: 2019,
      directors: [ "Jeff Tomsic" ],
      type: "movie"
    }
])
``` 
 
### **Query(Find) Documents in MongoDB**
[Watch here](https://youtu.be/9cWm74DteMQ?t=3622)

**Use the db.collection.find() method in the MongoDB Shell to *query(Find)* documents in a collection.**

#### **Read All Documents in a Collection**

To read all documents in the collection, pass an empty document as the query filter parameter to the find method.


```
db.movies.find()
``` 

#### **Specify Equality Condition**

  To select documents that match an equality condition, specify the condition as a **(field):(value)** pair in the *query filter document*.

To return all movies where the title equals Titanic from the sample_mflix.movies collection


```
use sample_mflix
db.movies.find( { "title": "Titanic" } )

```

#### **Specify Conditions Using Query Operators** 

Use query operators in a query filter document to perform more complex comparisons and evaluations. Query operators in a query filter document have the following form:


```
{ <field1>: { <operator1>: <value1> }, ... }
``` 

To return all movies from the sample_mflix.movies collection which are either released 2018 or 2019:


```
use sample_mflix
db.movies.find( { rated: { $in: [ "2018", "2019" ] } } )
``` 

### **Update Documents in MongoDB**
[Watch here](https://youtu.be/9cWm74DteMQ?t=5453)

**The MongoDB shell provides the following methods to update documents in a collection:**

- To update a single document, use **db.collection.updateOne()**.
- To update multiple documents, use **db.collection.updateMany()**.
- To replace a document, use **db.collection.replaceOne()**.

#### **Update Operator Syntax**

To update a document, MongoDB provides update operators, such as **$set**, to modify field values.
To use the update operators, pass to the update methods an update document of the form:


```
{
  <update operator>: { <field1>: <value1>, ... },
  <update operator>: { <field2>: <value2>, ... },
  ...
}
```
> Some update operators, such as **$set**, create the field if the field does not exist. 

#### **Update a Single Document**

Use the **db.collection.updateOne()** method to update the first document that matches a specified filter.

```
//To update the first document in the sample_mflix.movies collection where title equals "Tag":
use sample_mflix

db.movies.updateOne( { title: "Tag" },
{
  $set: {
    plot: "One month every year, five highly competitive friends
           hit the ground running for a no-holds-barred game of tag"
  }
  { $currentDate: { lastUpdated: true } }
})
``` 

#### **Update Multiple Documents**

   Use the **db.collection.updateMany()** to update all documents that match a specified filter.


```
//To update all documents in the sample_airbnb.listingsAndReviews 
//collection to update where security_deposit is less than 100:

use sample_airbnb

db.listingsAndReviews.updateMany(
  { security_deposit: { $lt: 100 } },
  {
    $set: { security_deposit: 100, minimum_nights: 1 }
  }
)
```

#### **Replace a Document**

To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to **db.collection.replaceOne()**.


```
//To replace the first document from the sample_analytics.accounts
// collection where account_id: 371138:
db.accounts.replaceOne(
  { account_id: 371138 },
  { account_id: 893421, limit: 5000, products: [ "Investment", "Brokerage" ] }
)
```

#### **Delete Documents**
[Watch here](https://youtu.be/9cWm74DteMQ?t=6377)

The MongoDB shell provides the following methods to delete documents from a collection:

- To delete multiple documents, use **db.collection.deleteMany()**.
- To delete a single document, use  **db.collection.deleteOne()**.

#### **Delete All Documents**

To delete all documents from a collection, pass an empty filter document {} to the **db.collection.deleteMany()** method.


```
//To delete all documents from the sample_mflix.movies collection:

use sample_mflix
db.movies.deleteMany({})
``` 

#### **Delete Only One Document that Matches a Condition**

To delete at most a single document that matches a specified filter (even though multiple documents may match the specified filter) use the **db.collection.deleteOne()** method.


```
//To delete the first document from the sample_mflix.movies collection 
//where the director array contains "Jeff Tomsic":

use sample_mflix
db.movies.deleteOne( { directors: "Jeff Tomsic" } )
``` 

That's All you need to know about MongoDB

![finally.webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1661167500014/W1u8778e_.webp)

So Far We have learned a lot. Do ask questions for clarifications and make corrections & suggestions, I expect them. That is all from my end, please share your views in the comment section, and thanks for reading it. Check out my other article [Here](https://sarthaksavvy.hashnode.dev/). Also, Subscribe to my [newsletter](https://bitfumes.com/newsletters). Follow me on [Socials](https://t.co/7bEAASotYQ). Happy Learning and Coding

![200w (1).webp](https://cdn.hashnode.com/res/hashnode/image/upload/v1661167487222/D8EiCiQnY.webp)


#### **[Subscribe To My YouTube channel](https://www.youtube.com/bitfumes?sub_confirmation=1)**

#### **[Follow me on Twitter](https://twitter.com/Sarthaksavvy)**


 **THANK YOU SO MUCH FOR YOUR TIME**