Unit 4 - Notes

INT222

Unit 4: Getting Started with MongoDB & Introduction to Mongoose

1. Introduction to MongoDB

What is MongoDB?

MongoDB is an open-source, NoSQL (Not Only SQL) database management system. Unlike traditional relational databases (RDBMS) like MySQL or PostgreSQL that use tables and rows, MongoDB uses a document-oriented data model.

Key Characteristics

  • Document-Oriented: Stores data in flexible, JSON-like documents (BSON).
  • Schema-less: The structure of documents can differ within the same collection. Fields can be added or removed on the fly.
  • Scalability: Built for high availability and horizontal scaling (Sharding).
  • High Performance: Supports indexing, replication, and load balancing.

MongoDB vs. RDBMS (SQL)

Feature RDBMS (e.g., MySQL) MongoDB
Data Structure Tables, Rows, Columns Collections, Documents, Fields
Schema Fixed (Defined before insertion) Dynamic (Flexible)
Relationships Complex Joins Embedded Documents or References
Query Language SQL MQL (MongoDB Query Language)

2. MongoDB Installation

Database Installation (Community Edition)

  1. Download: Visit the official MongoDB Download Center and select the Community Server for your OS (Windows, macOS, or Linux).
  2. Install: Run the .msi (Windows) or .tgz (Mac/Linux) installer.
  3. Data Directory: Create a folder to store data (default is usually C:\data\db on Windows or /data/db on Linux/Mac).
  4. Environment Variables: Add the MongoDB bin directory to your system's PATH variable to run commands globally.

MongoDB Shell (mongosh) Installation

Modern MongoDB versions separate the server from the shell.

  1. Download mongosh (MongoDB Shell) from the official site.
  2. Install and add to the system PATH.

Verifying Installation

Open a terminal/command prompt and run:

  • mongod: Starts the MongoDB server process (daemon).
  • mongosh: Opens the interactive JavaScript shell to communicate with the server.

3. MongoDB Terminology

1. Database

A physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server can hold multiple databases.

2. Collection

A group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema (unless validation rules are explicitly set).

3. Document

A set of key-value pairs. Documents have dynamic schemas. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields may hold different types of data. It is the equivalent of an RDBMS row.

4. Field

A key-value pair in a document. It is the equivalent of an RDBMS column.


4. Getting Familiar with Documents and Collections

BSON (Binary JSON)

While MongoDB looks like JSON, it stores data in BSON format. BSON extends the JSON model to provide additional data types (like Date and ObjectId) and to be efficient for encoding and decoding in different languages.

The _id Field

Every document in MongoDB requires a unique _id field that acts as a primary key.

  • If you do not provide an _id field upon insertion, MongoDB automatically generates a unique ObjectId.
  • ObjectId is a 12-byte BSON type (4-byte timestamp, 5-byte random value, 3-byte incrementing counter).

Example Document Structure

JSON
{
  "_id": ObjectId("507f1f77bcf86cd799439011"),
  "name": "John Doe",
  "age": 25,
  "skills": ["JavaScript", "MongoDB", "Node.js"],
  "address": {
    "city": "New York",
    "zip": "10001"
  },
  "isActive": true
}


5. MongoDB Shell Commands

The MongoDB Shell (mongosh) is a JavaScript interface.

Database Management

  • Show Databases: Lists all databases on the server.
    JAVASCRIPT
        show dbs
        
  • Create/Switch Database:
    JAVASCRIPT
        use myDatabase
        

    Note: MongoDB uses "Lazy Creation." The database is not physically created until you insert the first document into a collection.
  • Drop Database: Deletes the currently selected database.
    JAVASCRIPT
        db.dropDatabase()
        

Collection Management

  • Create Collection: (Explicit creation)
    JAVASCRIPT
        db.createCollection("users")
        

    Note: Collections are usually created implicitly when you insert a document (e.g., db.users.insertOne(...)).
  • Show Collections:
    JAVASCRIPT
        show collections
        
  • Drop Collection:
    JAVASCRIPT
        db.users.drop()
        

6. Data Manipulation (Shell CRUD Operations)

Create (Insert)

  • Insert One: Adds a single document.
    JAVASCRIPT
        db.users.insertOne({ name: "Alice", age: 30, role: "Admin" })
        
  • Insert Many: Adds multiple documents via an array.
    JAVASCRIPT
        db.users.insertMany([
          { name: "Bob", age: 22 },
          { name: "Charlie", age: 28 }
        ])
        

Read (Find)

  • Find All: Returns all documents in a collection.
    JAVASCRIPT
        db.users.find()
        
  • Format Output: Makes the JSON readable.
    JAVASCRIPT
        db.users.find().pretty()
        
  • Filter/Query: Find documents matching a condition.
    JAVASCRIPT
        // Find user where name is "Alice"
        db.users.find({ name: "Alice" })
        
        // Find users older than 25 ($gt = Greater Than)
        db.users.find({ age: { $gt: 25 } })
        
  • Find One: Returns the first matching document.
    JAVASCRIPT
        db.users.findOne({ name: "Bob" })
        

Update

  • Update One: Updates the first document that matches. Requires atomic operators like $set.
    JAVASCRIPT
        // Change Alice's age to 31
        db.users.updateOne(
          { name: "Alice" },       // Filter
          { $set: { age: 31 } }    // Update Action
        )
        
  • Update Many: Updates all documents that match.
    JAVASCRIPT
        // Set 'isActive' to true for all users
        db.users.updateMany(
          {}, 
          { $set: { isActive: true } }
        )
        

Delete

  • Delete One: Removes the first matching document.
    JAVASCRIPT
        db.users.deleteOne({ name: "Bob" })
        
  • Delete Many: Removes all matching documents.
    JAVASCRIPT
        db.users.deleteMany({ age: { $lt: 25 } }) // Delete users younger than 25
        

7. Connecting MongoDB using Node.js

To connect Node.js to MongoDB, you use the official MongoDB Native Driver.

Installation

BASH
npm install mongodb

Basic Connection and CRUD Code

JAVASCRIPT
const { MongoClient } = require('mongodb');

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myProject';

async function main() {
  try {
    // 1. Connect to server
    await client.connect();
    console.log('Connected successfully to server');
    
    const db = client.db(dbName);
    const collection = db.collection('documents');

    // 2. Insert
    const insertResult = await collection.insertOne({ a: 1 });
    console.log('Inserted documents:', insertResult);

    // 3. Find
    const findResult = await collection.find({ a: 1 }).toArray();
    console.log('Found documents:', findResult);

  } catch (error) {
    console.error(error);
  } finally {
    // 4. Close connection
    await client.close();
  }
}

main();


8. Introduction to Mongoose

What is Mongoose?

Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

Why use Mongoose over the Native Driver?

  1. Schemas: Enforces structure on documents (making them look more like SQL tables for consistency).
  2. Validation: Built-in validation (e.g., required: true, min: 18).
  3. Middleware: Hooks to run functions before/after saving (e.g., hashing passwords).
  4. Type Casting: Automatically converts data to the defined type.

Installation

BASH
npm install mongoose

Connecting Mongoose

JAVASCRIPT
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/myDatabase')
  .then(() => console.log('Connected to MongoDB via Mongoose'))
  .catch(err => console.error('Connection error:', err));


9. Schema Definition and Models

Schema

A Schema maps to a MongoDB collection and defines the shape of the documents within that collection.

JAVASCRIPT
const mongoose = require('mongoose');
const { Schema } = mongoose;

// Define the Schema
const userSchema = new Schema({
  name: {
    type: String,
    required: true // Validation
  },
  email: {
    type: String,
    unique: true
  },
  age: Number,
  createdAt: {
    type: Date,
    default: Date.now // Default value
  }
});

Model

To use the schema definition, we convert it into a Model. A model is a class with which we construct documents.

JAVASCRIPT
// Create the Model
// 'User' will be automatically pluralized to 'users' collection in MongoDB
const User = mongoose.model('User', userSchema);

module.exports = User;


10. Mongoose CRUD Operations

Using the User model defined above:

Create

JAVASCRIPT
// Method 1: Create instance and save
const newUser = new User({ name: "John", email: "john@example.com", age: 30 });
await newUser.save();

// Method 2: Use .create() shortcut
await User.create({ name: "Jane", email: "jane@example.com", age: 25 });

Read

JAVASCRIPT
// Find all
const allUsers = await User.find({});

// Find with filter (select specific fields)
const specificUser = await User.findOne({ email: "john@example.com" });

// Find by ID
const userById = await User.findById("64f8a...");

Update

JAVASCRIPT
// Find by ID and Update
// { new: true } returns the updated document rather than the original
const updatedUser = await User.findByIdAndUpdate(
  "64f8a...", 
  { age: 31 }, 
  { new: true }
);

// Update based on condition
await User.updateOne({ name: "Jane" }, { age: 26 });

Delete

JAVASCRIPT
// Find by ID and Delete
await User.findByIdAndDelete("64f8a...");

// Delete based on condition
await User.deleteOne({ name: "John" });