NOSQL

Introduction to NoSQL | Mongo DB

Table of Contents

  1. Introduction to NoSQL
  2. MongoDB
  3. Sample Project: Real-Time Data Storage with MongoDB
  4. Conclusion and Next Steps

Introduction to NoSQL

A Brief History of NoSQL

The journey of NoSQL databases began over several decades, with origins in hierarchical and file-based databases before becoming what we know today as “NoSQL.”

NoSQL was first coined in 1998 by Carlo Strozzi to name a file-based database he developed. Ironically, this NoSQL database was actually relational but didn’t use SQL as its interface. Later, in 2009, the term resurfaced when Eric Evans used it to describe the new wave of non-relational databases.

Key Milestones in NoSQL History

  • 1960s: Databases like MultiValue (PICK) and IBM IMS, used in Apollo missions, marked the beginnings of hierarchical data storage.
  • 1970s: Notable developments included Mumps at Mass General Hospital and DBM at AT&T.
  • 1980s-90s: The rise of Lotus Notes (a document database), GDBM by GNU, and Mnesia for telecom signaled increased experimentation.
  • 2000s: The NoSQL movement accelerated with the creation of systems like Neo4j (graph database), Memcached (caching layer), CouchDB (document store), and Google BigTable, influencing modern non-relational databases.

For a more detailed timeline, see NoSQL’s History.


MongoDB

MongoDB, a document-based database, was launched in 2007 as part of an open-source cloud computing stack and had its first standalone release in 2009. It quickly gained popularity for its JSON-like document structure, which allows for flexible, dynamic schemas, making it perfect for handling unstructured data.

MongoDB is known for:

  • High Scalability: Sharding enables MongoDB to scale horizontally across clusters.
  • Flexibility: JSON-like BSON format provides flexible schemas that adjust to data evolution.
  • Data Storage & Retrieval Efficiency: An efficient system for real-time data storage and retrieval.

Install MongoDB on Mac

To install MongoDB on macOS, we’ll use Homebrew.

Prerequisites

  1. Xcode Command-Line Tools: Install by running:
    bash
    Xcode-select --install
  2. Homebrew: If not installed, refer to the official Homebrew installation guide.
  3. MongoDB Tap: Ensure MongoDB is included in your Homebrew by running:
    bash
    brew tap mongodb/brew

Installing MongoDB 4.4 Community Edition

With prerequisites complete, install MongoDB by executing:

bash
brew install [email protected]

If needed, Homebrew will automatically fetch dependencies like mongodb-database-tools.

For detailed guidance, check the MongoDB Homebrew installation documentation.


Sample Project: Real-Time Data Storage with MongoDB

This sample project demonstrates MongoDB’s flexibility and schema-free architecture by creating a real-time data storage service to handle dynamic data entries (e.g., customer data in a retail application).

Project Structure

plaintext
mongodb-sample-project/

├── config/
│ └── dbConfig.js
├── models/
│ └── customer.js
├── routes/
│ └── customerRoutes.js
├── app.js
└── package.json
  • config/dbConfig.js: MongoDB configuration file.
  • models/customer.js: Customer data schema.
  • routes/customerRoutes.js: API routes for CRUD operations.
  • app.js: Application’s entry point.

Step 1: Setup MongoDB Connection

In config/dbConfig.js, configure the MongoDB connection.

javascript

const mongoose = require('mongoose');

const connectDB = async () => {
try {
await mongoose.connect(‘mongodb://localhost:27017/sampleDB’, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log(‘MongoDB connected’);
} catch (error) {
console.error(‘Connection error:’, error);
}
};

module.exports = connectDB;

Step 2: Define Data Schema

In models/customer.js, create a flexible schema for customer data.

javascript

const mongoose = require('mongoose');

const customerSchema = new mongoose.Schema({
name: String,
email: String,
age: Number,
address: String,
purchaseHistory: [
{
item: String,
date: Date,
amount: Number,
},
],
});

module.exports = mongoose.model(‘Customer’, customerSchema);

Step 3: Create CRUD Operations

In routes/customerRoutes.js, create routes for basic CRUD operations.

javascript
const express = require('express');
const router = express.Router();
const Customer = require('../models/customer');
// Create a new customer
router.post(‘/customer’, async (req, res) => {
const customer = new Customer(req.body);
await customer.save();
res.send(customer);
});// Retrieve customers
router.get(‘/customers’, async (req, res) => {
const customers = await Customer.find();
res.send(customers);
});// Update a customer
router.put(‘/customer/:id’, async (req, res) => {
const customer = await Customer.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.send(customer);
});

// Delete a customer
router.delete(‘/customer/:id’, async (req, res) => {
await Customer.findByIdAndDelete(req.params.id);
res.send({ message: ‘Customer deleted’ });
});

module.exports = router;

Step 4: Configure the Application

In app.js, set up the Express app and integrate MongoDB.

javascript
const express = require('express');
const connectDB = require('./config/dbConfig');
const customerRoutes = require('./routes/customerRoutes');
const app = express();
connectDB();app.use(express.json());
app.use(‘/api’, customerRoutes);app.listen(3000, () => {
console.log(‘Server running on http://localhost:3000’);
});

Step 5: Testing and Validation

  1. Start MongoDB:
    bash
    brew services start mongodb/brew/[email protected]
  2. Run the Application:
    bash
    node app.js
  3. Testing CRUD Operations:
    • Use Postman or curl to test the API endpoints.
    • Verify data persistence in MongoDB by running queries in the Mongo shell.
    bash
    mongo
    > use sampleDB
    > db.customers.find()

Conclusion and Next Steps

In this blog, we explored NoSQL’s history and MongoDB’s foundational elements, followed by a practical, real-time data storage project demonstrating MongoDB’s strengths. As NoSQL databases continue to evolve, MongoDB remains a popular choice for applications needing high flexibility and scalability.

Stay tuned for future blogs, where we’ll delve deeper into MongoDB’s advanced features, including indexing, aggregation, and sharding.