Intro
Hey everyone!🤗 If you are a developer who is just starting to work with databases, or perhaps you already know the basics and are looking for a recap or a more in-deph understanding, I hope this article will help you.
When I learn something new, I like to dig deeper and understand the underlying logic to ensure everything is clear. That's why I have structured this article starting from the NoSQL fundamentals all the way to the internal data storage mechanisms, concentrating on the why behind the database. So, I wish you happy reading!🥰
In this article, we will study:
- Where we Started: The SQL World
- The NoSQL story: Not Only SQL
- From localStorage to Database
- Basic CRUD Operations: Create, Read, Update, Delete
1. Where we Started: The SQL World
When we work with Relational Database like MySQL or PostgreSQL, our data lines up neatly in those perfectly organized tables. We have to make sure every single row follows a rigid column blueprint, decided right from the start. If we ever need to switch up that structure, we basically hit the brakes, tackle complex changes, and cross our fingers that all the existing data still fits.
We got consistency and logic out of this, sure, but as our apps kept scaling, that stiffnes became a real bottleneck for moving fast.
2. The NoSQL story: Not Only SQL
When it comes to NoSQL databases, you might have heard that it means No SQL, but let's clear things up: it's not a total war against SQL! The correct and modern interpretation is Not Only SQL❗
Why 'Not Only SQL'❓
Because we relize that SQL is a fantastic certain tasks (where strict relationship and consistency are vital), today's modern applications (social networks, gaming, websites) demand speed and flexibility. NoSQL is a supplement, an alternative that allows us to choose the right tool for the right job. We aren't giving up on SQL, we're just adding more powerful to our toolkit.
3. From localStorage to Database
Among the many types of NoSQL databases, MongoDB falls in to the Document-Oryented category.
Imagne no longer storing data across separate rows and columns. Instead, you store a complete record, for example, a user profile with all their addresses, orders, and preferences, in a single package called a Document.
Document:
→ The Document is the basic building block. It looks exactly like a JSON (JavaScript Object Notation) object, but, technically speacking, MongoDB uses BSON (Binary JSON). Why BSON❓ Because it's a faster binary format that also includes data types that simple JSON dosen't have (like date/ time values).
→ All these Documents (which, note, do not have to look identical) are grouped into a Collection, a kind of folder that replaces the old tables. To get an idea, we can think of documents as the value stored in localStorage, but they are much more powerful than a simple string value in localStorage❗
→ The Document is the smallest and most important unit of data in MongoDB, being the complete package of information that offers tremendous flexibility by allowing:
→ Storing nested objects,
→ Storing lists,
→ Direct storage of complex data types (such as Date/Time).
Here we have a Document:
{ // unique ID
"_id": ObjectId("61a5c6f0e8f0b7c4d5a9b8c7"),
// complex data type: Date/Time
"order_date": ISODate("2025-11-18T10:00:00Z"),
"status": "Shipped",
// nested object
"shipping_address": {
"street": "10 Example Blvd",
"city": "London",
"zip_code": "SW1A 0AA"
},
// list (Array)
"items": [
{
"product_name": "Laptop Pro",
"quantity": 1,
"price": 1200.00
},
{
"product_name": "Mouse Wireless",
"quantity": 2,
"price": 25.50
}
]
}
Colection:
→ If a Document is the equivalent of an individual record (like a complex value stored in localStorage or a row in a SQL table), the Collection in MongoDB is the folder that holds all those records together.
→The Collection is the conceptual equivalent of a Table in a relational (SQL) database. Unlike a SQL table, where all rows must adhere to the same structure (the same columns), Documents within a MongoDB Collection can have different structures (dynamic schema)❗
→ A small example, In MongoDB, we have a Database named school. This Database contains two Collections: students and teachers.
,
→ 1. The students Collection contains two documents:
{
first_name: "Alice",
last_name: "Smith",
age: 16,
grade: 10,
enrollment_date: new Date("2024-09-01T00:00:00Z"),
courses: ["Math", "Physics", "English"] // Array
},
{
first_name: "Bob",
last_name: "Johnson",
age: 17,
grade: 11,
enrollment_date: new Date("2023-09-01T00:00:00Z"),
contact: { // nested object
phone: "555-1234",
email: "bob@school.edu"
}
}
- The teachers
Collectioncontains two documents:
{
title: "Mr.",
last_name: "Davis",
subject: "Mathematics",
tenure: true,
phone: "555-5678"
class_count: 5
},
{
title: "Ms.",
last_name: "Garcia",
subject: "History",
class_count: 4,
office_hours: { // Nested Object
day: "Wednesday",
time: "2:00 PM - 3:00 PM"
}
}
Flexibility by Nature:
→ One user document might have a phone field, while the next one might not. This dynamic schema is the main reason developers choose MongoDB when dealing with data that evolves rapidly.
→ Therefore, MongoDB allows us to model data naturally, like objects (documents), and these objects are managed efficiently within logical groups called Collections.
The Essential Field: _id
→ Every Document must have a unique field named _id. This field serves as the Primary Key for the document (just like the unique ID in a SQL row).
→ If you don't specify an _id yourself when inserting data, MongoDB automatically generates one for you using a special data type called ObjectId. This ObjectId is guaranteed to be unique and even includes a timestamp, giving you information about the exact moment the document was created.
4. Basic CRUD Operations:
(Assuming the MongoDB server is installed and mongosh is ready, we can now connect to the database to see how we create collections and documents)...
→ CRUD operations represent the four basic functions that underlie any persistent data storage system. In the context of a database (such as MongoDB, although the terms apply generally), these are the methods through which we interact with Documents within a Collection.
1. Create: insertOne()/insertMany()
→ The Create operation adds new documents into a collection.
insertOne(document): this method is used to insert a single new document into the collection.
//this will add a new document in
//teachers collection
db.teachers.insertOne({
title: "Mr.",
last_name: "Jack",
subject: "Geography",
tenure: false,
phone: "555-5566"
class_count: 6
})
insertMany([document1, document2, ...]): this method is used to insert multiple documents into the collection with a single command. The argument is an array (list) of documents.
//this will add two documents in
//students collection
db.students.insertMany([
{
first_name: "Lea",
last_name: "Casy",
age: 17,
grade: 10
},
{
first_name: "Jessy",
last_name: "Smith",
age: 18,
grade: 10
}
])
2. Read: find()/findOne()
→ The Read operation retrieves documents from the collection based on filtering criteria.
findOne(query): this method returns the first document that matches the filtering criteria specified in the query object. It is ideal when you know you need a single document, for example, based on a unique ID. If no query is specified (i.e., it is empty: {}), it returns the first document found in the collection.
//find the first student with name 'Lea'
db.students.findOne({ first_name: 'Lea' })
find(query): This method returns a cursor to all documents that match the specified filtering criteria. If the query object is empty ({}), it returns all documents in the collection.
//return all of documents from students colection
db.students.find()
//find all students whose age is greater than 16
db.students.find({ age: {$gt: 16 }})
3. Update: updateOne()/updateMany()
updateOne(filter, update_operation): Updates the first document that matches the given filter.
//finds the document with `first_name 'Jessy'` and
// sets the new grade to false.
db.students.updateOne(
{ first_name: 'Jessy' },
{ $set: { grade: false } }
)
updateMany(filter, update_operation): Updates all documents that match the given filter.
// It selects documents only if the field contact is absent. ($exists: false)
// and add the 'contact' object with default phone and email values.
db.students.updateMany(
// 1. FILTER: Select documents missing the 'contact' field
{ contact: { $exists: false } },
// 2. OPERATION: Use $set to add the new 'contact' object
{
$set: {
"contact.phone": false,
"contact.email": "default@school.com"
}
}
);
→ The Basic $set Operator: This is the most common update operator. It specifies which fields should be modified and what their new values are. It either replaces the value of an existing field or adds a new field if it doesn't exist.
Basic Syntax: In update calls, the update operation part will often look like this: {"$set": {"field_name": "new_value", "another_field": 123}}.
4.Delete: deleteOne()/deleteMany
→ The Delete operation removes documents from the collection.
deleteOne(filter): deletes the first document that matches the specified filter.
// delete the first student found whose first name is 'Lea'.
db.students.deleteOne({ first_name: "Lea" })
deleteMany(filter): deletes all documents that match the specified filter.
// delete all students who are currently in grade 10.
db.students.deleteMany({ grade: 10 });
Caution❗If you use deleteMany({}) (an empty filter), you will delete all documents in the collection. Always be careful when using delete operations.🙃
Delete a colection: db.students.drop(),
Delete a database: first select the database use school, then we delete it db.dropDatabase()
Conclusion ❤️
While I haven't delved into the specifics of working tools, my goal for this first article was to provide a short but solid introduction to the fundamental of MongoDB.
There is a lot to explore in the world of MongoDB, but I believe these basics are essential. If you understand how data saving and retrieval work in localStorage, you can draw a useful analogy to better grasp collections within a database.🙃
I will be back soon with more detailed posts on the subject, further deepening the concepts we've learned. I hope this introductory guide was helpful!
If you enjoyed this article, learned something new, or if it brought back a smile thinking about your first attempts in MongoDB, don't forget to like the post or leave a comment! Thank you so much for reading and spending your valuable time with this article. I look forward to connecting with you in the next one! Happy codding!🥰🤗
Top comments (0)