Your Complete Guide to MongoDB: Part One ( Setup and Basics)
Tags: mongodb, nosql, javascript, database
Published: 2024-05-04 17:07:03

<h2>Table of Contents</h2>
<ul>
  <li><a href="#mongodb">What is MongoDB?</a></li>
  <li><a href="#sqldatabases">SQL Databases</a></li>
  <li><a href="#nosqldatabases">No-SQL Databases</a></li>
  <li><a href="#installation">Installation</a></li>
  <li><a href="#gettingstarted">Getting Started</a></li>
  <li><a href="#datatypes">Data Types</a></li>
  <li><a href="#combined">Combined Data Types</a></li>
  <li><a href="#mongodbcrudoperations">Mongodb Crud Operations</a>
  <li><a href="#create">Create</a>
  <li><a href="#read">Read</a>
  <li><a href="#update">Update</a>
  <li><a href="#delete">Delete</a>


</li>


</ul>

<hr>

<h2 id="mongodb">What is MongoDB?</h2>
<blockquote>
  <p>MongoDB is a NoSQL document-based database with schema flexibility, high scalability, and a rich query language.</p>
</blockquote>

<hr>

 <h2 id="sqldatabases">SQL Databases</h2>
<blockquote>
  <p>SQL stands for structured query language, which allows easy querying of data across multiple tables.</p>
  <ul>
    <li><strong>Pros:</strong>
      <ul>
        <li>Efficient queries due to its relational nature.</li>
        <li>Well-structured with low potential for errors.</li>
        <li>ACID Transactions (Atomicity, Consistency, Isolation, Durability).</li>
      </ul>
    </li>
    <li><strong>Cons:</strong>
      <ul>
        <li>Difficult to scale horizontally.</li>
        <li>Difficult to version control queries and schema changes.</li>
        <li>Heavy write operations are slow and expensive due to its use of ACID transactions and relation nature.</li>
      </ul>
    </li>
  </ul>
</blockquote>

<hr>

<h2 id="nosqldatabases">No-SQL Databases</h2>
<blockquote>
  <p>NoSQL stands for "not only SQL". NoSQL databases are designed to store and manage data differently than traditional relational databases which rely on SQL.</p>
</blockquote>

<blockquote>
  <ul>
    <li><strong>Pros:</strong>
      <ul>
        <li>Handles heavy writing operations better than SQL.</li>
        <li>Fast initial development with flexible data structures for future needs.</li>
        <li>Horizontally scaling is much easier than SQL databases like sharding.</li>
        <li>Rich Query Language.</li>
      </ul>
    </li>
    <li><strong>Cons:</strong>
      <ul>
        <li>Very few NoSQL database engines support ACID transactions like MongoDB (4.0 and later).</li>
        <li>In order to use the horizontal scaling may cause loss of consistency due to distribution of data.</li>
        <li>small user community.</li>
      </ul>
    </li>
  </ul>
</blockquote>

<blockquote>
  <p><strong>Note:</strong> Both systems are great you just have to find your use case.</p>
</blockquote>
<hr>

<h2 id="installation">Download Mongodb Gui and Terminal</h2>
<ul>
  <li>
    <a href="https://www.mongodb.com/products/tools/compass">Mongo Compass GUI</a>
  </li>
  <li>
    <a href="https://www.mongodb.com/try/download/compass">MongoDB Shell</a>
  </li>
</ul>

<hr>

<blockquote>
  <p>Mongodb is built based on collections, each containing documents.</p>
</blockquote>

<hr>

<blockquote>
  <h2>Mongodb Project hierarchy.</h2>
</blockquote>

```bash
Cluster
└── Database
    └── Collection
        └── Document // 
```

<hr>



<h2 id="gettingstarted">
  Getting Started
</h2>


<blockquote>
  <p>Open mongodb shell and type.</p>
</blockquote>
<blockquote>
  <p>To establish a connection to your local host.</p>
</blockquote>
```bash
mongosh 
```

<hr>

<blockquote>
  <p>To List Your Databases.</p>
</blockquote>
```bash
show dbs
```
<hr>



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



<hr>
<blockquote>
  <p>Using a database that doesn't exist creates a new one.</p>
</blockquote>
```bash
use shops
```

<hr>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bby01d477iawg4iolcjj.jpg)

<hr style="border: none; height: 0;">


<blockquote>
  <p>The new database is not visible because it's empty.</p>
</blockquote>

<hr>


<blockquote>
  <p>To create a new collection called restaurants.</p>
</blockquote>
```
db.createCollection("restaurants")
```
<hr style="border: none; height: 0;">

<blockquote>
  <p>to drop the current database your currently on.</p>
</blockquote>
```
db.dropDatabase()
```

<hr style="border: none; height: 0;">


<blockquote>
  <p>Now if you execute show dbs again it will show the new database(shops).</p>
</blockquote>



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

<hr>
<h2 id="datatypes">
  Data Types
</h2>
<blockquote>
  <dl>
    <dt>_id</dt>
    <dd>ObjectId: 12-byte identifier that is automatically generated for each document, serving as the primary key.</dd>
    <dt>Title</dt>
    <dt>shopRank</dt>
    <dd>Integer: Numerical value (32 bit or 64 bit).</dd>

    <dt>isClosed</dt>
    <dd>Boolean: Stores a boolean (true/false) value.</dd>

    <dt>location</dt>
    <dd>Object:
      <ul>
        <li>latitude: String</li>
        <li>longitude: String</li>
      </ul>
    </dd>

    <dt>tags</dt>
    <dd>Array: Array of strings.</dd>

    <dt>createdAt</dt>
    <dd>Timestamp: Records when the document has been added.</dd>

    <dt>updatedAt</dt>
    <dd>Timestamp: Records when the document has been modified.</dd>
  </dl>
</blockquote>



<hr>

<h2 id="combined">
  Combined Data Types
</h2>

```json
{
  "_id": "Randomly generated",
  "title":"String",
  "shopRank": "numeric value",
  "isClosed": "Boolean",
  "location":Object{
    "latitude": "Double",
  "longitude": "Double",
  },
  "tags": ["Arrays [String]"],
  "createdAt": "Timestamp automatically created",
  "updatedAt": "Timestamp automatically created"
}
```

<hr>

<h2 id="mongodbcrudoperations">
  Mongodb Crud Operations
</h2>

<hr>

<h2 id="create">
  Create
</h2>

<blockquote>
  <p>You can insert one document.</p>
</blockquote>


```
db.restaurants.insertOne(
 {
  "title": "Burger King",
  "shopRank": 10,
  "isClosed": true,
  "location":{
    "latitude": Double(-82.64761),
  	"longitude": Double(-82.64761),
  },
  "tags": ["burger","fries"],
  "createdAt":new Date(),
  "updatedAt":new Date()
 }
))
```

<hr>

<blockquote>
  <p>You can insert many documents.</p>
</blockquote>

```
db.restaurants.insertMany(
[
 {
  "title": "Bazooka",
  "shopRank": 5,
  "isClosed": false,
  "location":{
    "latitude": Double(-81.64761),
  	"longitude": Double(-81.64761),
  },
  "tags": ["fried chicken","cheese"],
  "createdAt":new Date(),
  "updatedAt":new Date()
 },
{
  "title": "Fake Salads",
  "shopRank": 9,
  "isClosed": true,
  "location":{
    "latitude": Double(-82.64761),
  	"longitude": Double(-82.64761),
  },
  "tags": ["salads","healthy"],
  "createdAt":new Date(),
  "updatedAt":new Date()
 },
]
)
```
<hr>

<h2 id="read">
  Read
</h2>

<blockquote>
  <p>To list down all documents with no filter.</p>
</blockquote>

```
db.restaurants.find({})
```

<hr>

<blockquote>
  <p>find documents with ranks lower than 10.</p>
</blockquote>

```
db.restaurants.find({
   shopRank:{
      $lt: 10
   }
})
```

<hr>

<blockquote>
  <p>Find restaurant named Bazooka.</p>
</blockquote>

```
db.restaurants.findOne({
   title:"Bazooka"
})
```

<hr>

<h2 id="update">
  Update
</h2>

<blockquote>
  <p>Update all restaurants to be open.</p> 
</blockquote>

```
db.restaurants.updateMany(
{},
 {
    $set: {
      isClosed: false
    }
 }
)
```

<hr>

<blockquote>
  <p>Update one restaurant to be closed with given id.</p> 
</blockquote>

```
db.restaurants.updateOne(
{
  _id: ObjectId("6636144f11737b3b326290e1")
},
 {
    $set: {
      isClosed: false
    }
 }
)
```

<hr>

<blockquote>
  <p>Update a restaurant tags to be empty.</p> 
</blockquote>

```
db.restaurants.updateOne(
{
  _id: ObjectId("663615ff11737b3b326290e3")
},
 {
    $set: {
      tags:[]
    }
 }
)
```

<hr>

<blockquote>
  <p>Update the same document with any tags you prefer.</p> 
</blockquote>

```
db.restaurants.updateOne(
{
  _id: ObjectId("663615ff11737b3b326290e3")
},
 {
    $pull: {
      tags: "caesar salad"
    }
 }
)
```

<hr>

<blockquote>
  <p>Push tag to tags array for any restaurant.</p> 
</blockquote>

```
db.restaurants.updateOne(
{
  _id: ObjectId("663615ff11737b3b326290e3")
},
 {
    $push: {
      tags: "fried chicken"
    }
 }
)
```


<hr>

<h2 id="delete">
  Delete
</h2>

<blockquote>
  <p>Delete document with given id.</p> 
</blockquote>

```
db.restaurants.deleteOne(
{
  _id: ObjectId("663615ff11737b3b326)

},
{}
)
```

<hr>

<blockquote>
  <p>Delete shops with rank higher than 5.</p> 
</blockquote>

```
db.restaurants.deleteMany(
{
 shopRank:{
   $gt: 5
}
},
{}
```
<hr>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2eglix8fhcxvmmd9aj3.jpg)
<hr>
<h2>Next parts</h2>
<ul>
  <li><a href="https://dev.to/hakimmohamed/your-complete-guide-to-mongodb-part-two-advanced-query-filtering-1o9i">Part two </a></li>
</li>


</ul>