Beginner’s Guide to MongoDB and Node.js: A Practical Approach
Step 0: Understanding MongoDB
MongoDB is a document-oriented database. Unlike relational databases:
-
There are no tables; instead, we use collections.
-
Records are called documents and are stored in JSON-like format.
-
MongoDB is schema-less, meaning documents in the same collection can have different fields.
Think of MongoDB as a digital notebook where each page is a structured JSON entry. 📒
Step 1: Install MongoDB and Node.js
-
Install MongoDB Community Server from the official website.
-
Install Node.js if you haven’t already.
-
Use MongoDB Compass (GUI) to visualize your database (optional but helpful).
Step 2: Set Up Node.js Project
Create a project folder:
Install the required Node.js packages:
-
Express → server framework
-
mongodb → official MongoDB Node.js driver
-
body-parser → parse JSON request bodies
Step 3: Connect to MongoDB
Create a file server.js:
Explanation:
-
MongoClient.connect()→ connects to the MongoDB server -
db.collection('employees')→ selects (or creates) a collection -
useUnifiedTopology: true→ modern connection management
Step 4: Insert Documents
Inside the MongoClient.connect() callback, add:
Explanation:
-
Documents are JSON-like objects (
{ key: value }) -
_idis automatically generated if not provided
Step 5: Read Documents
Explanation:
-
find({})→ retrieves all documents -
toArray()→ converts cursor to array for easier manipulation
Step 6: Update Documents
Explanation:
-
$set→ updates specific fields without affecting others -
updateOne()→ updates only the first matching document
Step 7: Delete Documents
Explanation:
-
deleteOne()removes a single matching document -
MongoDB also supports
deleteMany()for bulk deletions
Step 8: Wrap Up
In this tutorial, you learned:
-
The difference between relational and NoSQL databases
-
How to connect Node.js to MongoDB
-
How to insert, read, update, and delete documents
-
Why collections and documents are flexible and schema-less
MongoDB is ideal for projects where flexibility is important, and it integrates well with modern web applications.