Your Complete Guide to MongoDB: Part One ( Setup and Basics)
Abdelhakim mohamed
Posted on May 4, 2024
Table of Contents
- What is MongoDB?
- SQL Databases
- No-SQL Databases
- Installation
- Getting Started
- Data Types
- Combined Data Types
- Mongodb Crud Operations
- Create
- Read
- Update
- Delete
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 //
Getting Started
Open mongodb shell and type.
To establish a connection to your local host.
mongosh
To List Your Databases.
show dbs
Using a database that doesn't exist creates a new one.
use shops
The new database is not visible because it's empty.
To create a new collection called restaurants.
db.createCollection("restaurants")
to drop the current database your currently on.
db.dropDatabase()
Now if you execute show dbs again it will show the new database(shops).
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"
}
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()
}
))
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()
},
]
)
Read
To list down all documents with no filter.
db.restaurants.find({})
find documents with ranks lower than 10.
db.restaurants.find({
shopRank:{
$lt: 10
}
})
Find restaurant named Bazooka.
db.restaurants.findOne({
title:"Bazooka"
})
Update
Update all restaurants to be open.
db.restaurants.updateMany(
{},
{
$set: {
isClosed: false
}
}
)
Update one restaurant to be closed with given id.
db.restaurants.updateOne(
{
_id: ObjectId("6636144f11737b3b326290e1")
},
{
$set: {
isClosed: false
}
}
)
Update a restaurant tags to be empty.
db.restaurants.updateOne(
{
_id: ObjectId("663615ff11737b3b326290e3")
},
{
$set: {
tags:[]
}
}
)
Update the same document with any tags you prefer.
db.restaurants.updateOne(
{
_id: ObjectId("663615ff11737b3b326290e3")
},
{
$pull: {
tags: "caesar salad"
}
}
)
Push tag to tags array for any restaurant.
db.restaurants.updateOne(
{
_id: ObjectId("663615ff11737b3b326290e3")
},
{
$push: {
tags: "fried chicken"
}
}
)
Delete
Delete document with given id.
db.restaurants.deleteOne(
{
_id: ObjectId("663615ff11737b3b326)
},
{}
)
Delete shops with rank higher than 5.
db.restaurants.deleteMany(
{
shopRank:{
$gt: 5
}
},
{}
Next parts
Posted on May 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.