MongoDB Introduction - NoSQL Database Basics

beginner | 50 min read | 2024.12.29

What You’ll Learn in This Tutorial

✓ MongoDB setup
✓ CRUD operations
✓ Query operators
✓ Indexes
✓ Aggregation pipelines

Step 1: Setup

# macOS
brew tap mongodb/brew
brew install mongodb-community
brew services start mongodb-community

# Connect
mongosh

Step 2: Basic Operations

// Select database
use myapp

// Insert document
db.users.insertOne({
  name: "John Doe",
  email: "john@example.com",
  age: 30
})

db.users.insertMany([
  { name: "Jane Smith", email: "jane@example.com", age: 25 },
  { name: "Bob Wilson", email: "bob@example.com", age: 35 }
])

Step 3: Queries

// Get all
db.users.find()

// Conditional query
db.users.find({ age: { $gte: 30 } })

// Operators
db.users.find({
  $and: [
    { age: { $gte: 25 } },
    { age: { $lte: 35 } }
  ]
})

// Projection
db.users.find({}, { name: 1, email: 1, _id: 0 })

// Sort and limit
db.users.find().sort({ age: -1 }).limit(10)

Step 4: Update and Delete

// Update
db.users.updateOne(
  { email: "john@example.com" },
  { $set: { age: 31 } }
)

// Update many
db.users.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

// Delete
db.users.deleteOne({ email: "john@example.com" })

Step 5: Indexes

// Create index
db.users.createIndex({ email: 1 }, { unique: true })

// Compound index
db.users.createIndex({ age: 1, name: 1 })

// Check indexes
db.users.getIndexes()

Step 6: Aggregation Pipeline

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: {
      _id: "$userId",
      totalAmount: { $sum: "$amount" },
      count: { $sum: 1 }
  }},
  { $sort: { totalAmount: -1 } },
  { $limit: 10 }
])

Step 7: Node.js Integration

import { MongoClient } from 'mongodb';

const client = new MongoClient('mongodb://localhost:27017');
await client.connect();

const db = client.db('myapp');
const users = db.collection('users');

const result = await users.find({ age: { $gte: 30 } }).toArray();
console.log(result);

await client.close();

Summary

MongoDB handles JSON-format documents with flexible schemas. Complex analysis is also possible with aggregation pipelines.

← Back to list