Advertisement
programming This tutorial provides a structured, clear approach to learning MongoDB, a popular NoSQL database, using Node.js. You will understand how to connect to MongoDB, create collections, perform CRUD operations, and work with JSON-like documents. All explanations are detailed and suitable for beginners who want a solid understanding of NoSQL databases.

Beginner’s Guide to MongoDB and Node.js: A Practical Approach

5 Min Read Verified Content

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

  1. Install MongoDB Community Server from the official website.

  2. Install Node.js if you haven’t already.

  3. Use MongoDB Compass (GUI) to visualize your database (optional but helpful).


Step 2: Set Up Node.js Project

Create a project folder:

mkdir mongodb-nodejs-demo cd mongodb-nodejs-demo npm init -y

Install the required Node.js packages:

npm install express mongodb body-parser
  • 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:

const express = require('express'); const bodyParser = require('body-parser'); const { MongoClient } = require('mongodb'); const app = express(); app.use(bodyParser.json()); const PORT = 3000; const url = 'mongodb://localhost:27017'; const dbName = 'company_db'; MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => { if (err) throw err; console.log('Connected to MongoDB successfully!'); const db = client.db(dbName); const employees = db.collection('employees'); // Test endpoint app.get('/', (req, res) => { res.send('MongoDB Node.js API is running.'); }); app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); }); });

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:

// Insert one employee employees.insertOne({ name: 'Alice Smith', email: 'alice@example.com', position: 'Developer', salary: 5000 }, (err, result) => { if (err) throw err; console.log('Employee inserted:', result.insertedId); });

Explanation:

  • Documents are JSON-like objects ({ key: value })

  • _id is automatically generated if not provided



Step 5: Read Documents

// Fetch all employees employees.find({}).toArray((err, docs) => { if (err) throw err; console.log('Employees:', docs); });

Explanation:

  • find({}) → retrieves all documents

  • toArray() → converts cursor to array for easier manipulation



Step 6: Update Documents

// Update employee salary employees.updateOne( { name: 'Alice Smith' }, { $set: { salary: 5500 } }, (err, result) => { if (err) throw err; console.log('Documents updated:', result.modifiedCount); } );

Explanation:

  • $set → updates specific fields without affecting others

  • updateOne() → updates only the first matching document



Step 7: Delete Documents

// Delete an employee employees.deleteOne({ name: 'Alice Smith' }, (err, result) => { if (err) throw err; console.log('Documents deleted:', result.deletedCount); });

Explanation:

  • deleteOne() removes a single matching document

  • MongoDB also supports deleteMany() for bulk deletions



Step 8: Wrap Up

In this tutorial, you learned:

  1. The difference between relational and NoSQL databases

  2. How to connect Node.js to MongoDB

  3. How to insert, read, update, and delete documents

  4. 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.

Advertisement
Back to Programming