Javascript 101

MongoDB

MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents.

Basic Query Commands

Connecting to MongoDB Shell

mongosh # Connect to local MongoDB
mongosh "mongodb://host:port/db" # Connect to remote

Database Operations

show dbs // List all databases
use myDatabase // Switch to/create database
db.dropDatabase() // Delete current database

Collection Operations

show collections // List collections
db.createCollection("users") // Create collection
db.users.drop() // Delete collection

Insert Documents

// Insert one document
db.users.insertOne({
name: "John",
age: 30,
email: "john@example.com",
});
// Insert multiple documents
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 },
]);

Query Documents

// Find all documents
db.users.find();
// Find with condition
db.users.find({ age: 30 });
// Find one document
db.users.findOne({ name: "John" });
// Comparison operators
db.users.find({ age: { $gt: 25 } }); // Greater than
db.users.find({ age: { $gte: 25 } }); // Greater than or equal
db.users.find({ age: { $lt: 30 } }); // Less than
db.users.find({ age: { $lte: 30 } }); // Less than or equal
db.users.find({ age: { $ne: 30 } }); // Not equal
// Logical operators
db.users.find({ $and: [{ age: { $gt: 20 } }, { age: { $lt: 40 } }] });
db.users.find({ $or: [{ name: "John" }, { name: "Alice" }] });
// Projection (select specific fields)
db.users.find({}, { name: 1, email: 1, _id: 0 });
// Sorting
db.users.find().sort({ age: 1 }); // Ascending
db.users.find().sort({ age: -1 }); // Descending
// Limit and skip
db.users.find().limit(5);
db.users.find().skip(10).limit(5);

Update Documents

// Update one document
db.users.updateOne({ _id: ObjectId("507f1f77bcf86cd799439011") }, { $set: { age: 31 } });
// Update multiple documents
db.users.updateMany({ age: { $lt: 30 } }, { $set: { status: "young" } });
// Replace entire document
db.users.replaceOne(
{ _id: ObjectId("507f1f77bcf86cd799439011") },
{ name: "John", age: 31, city: "New York" },
);
// Update operators
db.users.updateOne({ name: "John" }, { $inc: { age: 1 } }); // Increment
db.users.updateOne({ name: "John" }, { $unset: { email: "" } }); // Remove field
db.users.updateOne({ name: "John" }, { $push: { tags: "new" } }); // Add to array

Delete Documents

// Delete one document
db.users.deleteOne({ _id: ObjectId("507f1f77bcf86cd799439011") });
// Delete multiple documents
db.users.deleteMany({ age: { $lt: 20 } });
// Delete all documents
db.users.deleteMany({});

Indexing

// Create index
db.users.createIndex({ email: 1 });
// Create unique index
db.users.createIndex({ email: 1 }, { unique: true });
// List indexes
db.users.getIndexes();
// Drop index
db.users.dropIndex("email_1");

MongoDB with Node.js

Installation

npm install mongodb

Connecting to MongoDB

const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function connect() {
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db("myDatabase");
return db;
} catch (error) {
console.error("Connection error:", error);
}
}

CRUD Operations in Node.js

const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
const db = client.db("myDatabase");
const users = db.collection("users");
// Insert
const insertResult = await users.insertOne({
name: "John",
age: 30,
email: "john@example.com",
});
console.log("Inserted:", insertResult.insertedId);
// Find
const user = await users.findOne({ name: "John" });
console.log("Found:", user);
// Find all with cursor
const cursor = users.find({ age: { $gte: 25 } });
const allUsers = await cursor.toArray();
console.log("All users:", allUsers);
// Update
const updateResult = await users.updateOne(
{ name: "John" },
{ $set: { age: 31 } },
);
console.log("Updated:", updateResult.modifiedCount);
// Delete
const deleteResult = await users.deleteOne({ name: "John" });
console.log("Deleted:", deleteResult.deletedCount);
} finally {
await client.close();
}
}
main().catch(console.error);

Using with Express.js

const express = require("express");
const { MongoClient, ObjectId } = require("mongodb");
const app = express();
app.use(express.json());
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
let db;
// Connect on startup
client.connect().then(() => {
db = client.db("myDatabase");
console.log("Connected to MongoDB");
});
// GET all users
app.get("/users", async (req, res) => {
const users = await db.collection("users").find().toArray();
res.json(users);
});
// GET user by ID
app.get("/users/:id", async (req, res) => {
const user = await db.collection("users").findOne({
_id: new ObjectId(req.params.id),
});
if (!user) return res.status(404).json({ error: "User not found" });
res.json(user);
});
// POST create user
app.post("/users", async (req, res) => {
const result = await db.collection("users").insertOne(req.body);
res.status(201).json({ id: result.insertedId });
});
// PUT update user
app.put("/users/:id", async (req, res) => {
const result = await db
.collection("users")
.updateOne({ _id: new ObjectId(req.params.id) }, { $set: req.body });
res.json({ modified: result.modifiedCount });
});
// DELETE user
app.delete("/users/:id", async (req, res) => {
const result = await db.collection("users").deleteOne({
_id: new ObjectId(req.params.id),
});
res.json({ deleted: result.deletedCount });
});
app.listen(3000, () => console.log("Server running on port 3000"));

Using Mongoose (ODM)

Mongoose provides schema validation and a more structured approach.

npm install mongoose
const mongoose = require("mongoose");
// Connect
mongoose.connect("mongodb://localhost:27017/myDatabase");
// Define schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
age: { type: Number, min: 0 },
email: { type: String, unique: true },
createdAt: { type: Date, default: Date.now },
});
// Create model
const User = mongoose.model("User", userSchema);
// CRUD operations
async function main() {
// Create
const user = new User({ name: "John", age: 30, email: "john@example.com" });
await user.save();
// Read
const users = await User.find({ age: { $gte: 25 } });
const john = await User.findOne({ name: "John" });
// Update
await User.updateOne({ name: "John" }, { age: 31 });
// or
john.age = 31;
await john.save();
// Delete
await User.deleteOne({ name: "John" });
}
main().catch(console.error);