Your Complete Guide to MongoDB: Part One ( Setup and Basics)

hakimmohamed

Abdelhakim mohamed

Posted on May 4, 2024

Your Complete Guide to MongoDB: Part One ( Setup and Basics)

Table of Contents


What is MongoDB?

MongoDB is a NoSQL document-based database with schema flexibility, high scalability, and a rich query language.


SQL Databases

SQL stands for structured query language, which allows easy querying of data across multiple tables.

  • Pros:
    • Efficient queries due to its relational nature.
    • Well-structured with low potential for errors.
    • ACID Transactions (Atomicity, Consistency, Isolation, Durability).
  • Cons:
    • Difficult to scale horizontally.
    • Difficult to version control queries and schema changes.
    • Heavy write operations are slow and expensive due to its use of ACID transactions and relation nature.


No-SQL Databases

NoSQL stands for "not only SQL". NoSQL databases are designed to store and manage data differently than traditional relational databases which rely on SQL.

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

Note: Both systems are great you just have to find your use case.


Download Mongodb Gui and Terminal


Mongodb is built based on collections, each containing documents.


Mongodb Project hierarchy.

Cluster
└── Database
    └── Collection
        └── Document // 
Enter fullscreen mode Exit fullscreen mode

Getting Started

Open mongodb shell and type.

To establish a connection to your local host.

mongosh 
Enter fullscreen mode Exit fullscreen mode

To List Your Databases.

show dbs
Enter fullscreen mode Exit fullscreen mode

Image description


Using a database that doesn't exist creates a new one.

use shops
Enter fullscreen mode Exit fullscreen mode


Image description

The new database is not visible because it's empty.


To create a new collection called restaurants.

db.createCollection("restaurants")
Enter fullscreen mode Exit fullscreen mode

to drop the current database your currently on.

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Now if you execute show dbs again it will show the new database(shops).

Image description


Data Types

_id
ObjectId: 12-byte identifier that is automatically generated for each document, serving as the primary key.
Title
shopRank
Integer: Numerical value (32 bit or 64 bit).
isClosed
Boolean: Stores a boolean (true/false) value.
location
Object:
  • latitude: String
  • longitude: String
tags
Array: Array of strings.
createdAt
Timestamp: Records when the document has been added.
updatedAt
Timestamp: Records when the document has been modified.

Combined Data Types

{
  "_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"
}
Enter fullscreen mode Exit fullscreen mode

Mongodb Crud Operations


Create

You can insert one document.

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()
 }
))
Enter fullscreen mode Exit fullscreen mode

You can insert many documents.

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()
 },
]
)
Enter fullscreen mode Exit fullscreen mode

Read

To list down all documents with no filter.

db.restaurants.find({})
Enter fullscreen mode Exit fullscreen mode

find documents with ranks lower than 10.

db.restaurants.find({
   shopRank:{
      $lt: 10
   }
})
Enter fullscreen mode Exit fullscreen mode

Find restaurant named Bazooka.

db.restaurants.findOne({
   title:"Bazooka"
})
Enter fullscreen mode Exit fullscreen mode

Update

Update all restaurants to be open.

db.restaurants.updateMany(
{},
 {
    $set: {
      isClosed: false
    }
 }
)
Enter fullscreen mode Exit fullscreen mode

Update one restaurant to be closed with given id.

db.restaurants.updateOne(
{
  _id: ObjectId("6636144f11737b3b326290e1")
},
 {
    $set: {
      isClosed: false
    }
 }
)
Enter fullscreen mode Exit fullscreen mode

Update a restaurant tags to be empty.

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

Update the same document with any tags you prefer.

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

Push tag to tags array for any restaurant.

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

Delete

Delete document with given id.

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

},
{}
)
Enter fullscreen mode Exit fullscreen mode

Delete shops with rank higher than 5.

db.restaurants.deleteMany(
{
 shopRank:{
   $gt: 5
}
},
{}
Enter fullscreen mode Exit fullscreen mode

Image description


Next parts

💖 💪 🙅 🚩
hakimmohamed
Abdelhakim mohamed

Posted on May 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related