Kembali ke Blog
Cara Menggunakan MongoDB untuk Database NoSQL
MongoDB adalah database NoSQL yang flexible dan scalable. Mari pelajari cara menggunakannya.
Install MongoDB
Ubuntu/Debian
# Import public key
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
--dearmor
# Add repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# Install
sudo apt update
sudo apt install -y mongodb-org
# Start service
sudo systemctl start mongod
sudo systemctl enable mongod
# Verify
mongosh
Docker
docker run -d \
--name mongodb \
-p 27017:27017 \
-v mongodb-data:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password \
mongo:7
MongoDB Shell (mongosh)
Basic Commands
// Show databases
show dbs
// Use/create database
use mydb
// Show collections
show collections
// Create collection
db.createCollection("users")
// Drop database
db.dropDatabase()
// Drop collection
db.users.drop()
CRUD Operations
Create (Insert)
// Insert one document
db.users.insertOne({
name: "Budi",
email: "budi@email.com",
age: 25,
roles: ["user", "admin"],
address: {
city: "Jakarta",
zip: "12345",
},
createdAt: new Date(),
});
// Insert many documents
db.users.insertMany([
{ name: "Ani", email: "ani@email.com", age: 23 },
{ name: "Citra", email: "citra@email.com", age: 28 },
{ name: "Deni", email: "deni@email.com", age: 30 },
]);
Read (Find)
// Find all
db.users.find();
// Find with pretty print
db.users.find().pretty();
// Find one
db.users.findOne({ name: "Budi" });
// Find with conditions
db.users.find({ age: { $gt: 25 } });
db.users.find({ age: { $gte: 25, $lte: 30 } });
db.users.find({ name: { $in: ["Budi", "Ani"] } });
// Find with AND
db.users.find({
age: { $gt: 20 },
"address.city": "Jakarta",
});
// Find with OR
db.users.find({
$or: [{ age: { $lt: 25 } }, { roles: "admin" }],
});
// Projection (select fields)
db.users.find({}, { name: 1, email: 1, _id: 0 });
// Sort
db.users.find().sort({ age: 1 }); // Ascending
db.users.find().sort({ age: -1 }); // Descending
// Limit and skip
db.users.find().limit(10);
db.users.find().skip(10).limit(10); // Pagination
// Count
db.users.countDocuments({ age: { $gt: 25 } });
Update
// Update one
db.users.updateOne({ name: "Budi" }, { $set: { age: 26 } });
// Update many
db.users.updateMany({ age: { $lt: 25 } }, { $set: { status: "junior" } });
// Increment
db.users.updateOne({ name: "Budi" }, { $inc: { age: 1 } });
// Push to array
db.users.updateOne({ name: "Budi" }, { $push: { roles: "editor" } });
// Pull from array
db.users.updateOne({ name: "Budi" }, { $pull: { roles: "user" } });
// Upsert (insert if not exists)
db.users.updateOne(
{ email: "new@email.com" },
{ $set: { name: "New User", age: 20 } },
{ upsert: true }
);
// Replace document
db.users.replaceOne(
{ name: "Budi" },
{ name: "Budi", email: "budi.new@email.com", age: 27 }
);
Delete
// Delete one
db.users.deleteOne({ name: "Budi" });
// Delete many
db.users.deleteMany({ age: { $lt: 20 } });
// Delete all
db.users.deleteMany({});
Indexes
Create Indexes
// Single field index
db.users.createIndex({ email: 1 });
// Compound index
db.users.createIndex({ name: 1, age: -1 });
// Unique index
db.users.createIndex({ email: 1 }, { unique: true });
// Text index
db.articles.createIndex({ title: "text", content: "text" });
// TTL index (auto-delete after time)
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });
Index Management
// List indexes
db.users.getIndexes();
// Drop index
db.users.dropIndex("email_1");
// Explain query (show index usage)
db.users.find({ email: "budi@email.com" }).explain("executionStats");
Aggregation Pipeline
Basic Aggregation
// Match and group
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$group: {
_id: "$customerId",
totalAmount: { $sum: "$amount" },
orderCount: { $sum: 1 },
},
},
{ $sort: { totalAmount: -1 } },
{ $limit: 10 },
]);
Common Stages
// $match - Filter documents
{ $match: { status: "active" } }
// $group - Group and aggregate
{ $group: {
_id: "$category",
total: { $sum: "$price" },
average: { $avg: "$price" },
count: { $sum: 1 },
items: { $push: "$name" }
}}
// $project - Shape output
{ $project: {
name: 1,
email: 1,
fullName: { $concat: ["$firstName", " ", "$lastName"] },
_id: 0
}}
// $lookup - Join collections
{ $lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "userOrders"
}}
// $unwind - Deconstruct array
{ $unwind: "$tags" }
// $sort
{ $sort: { createdAt: -1 } }
// $skip and $limit
{ $skip: 10 }
{ $limit: 10 }
Complex Example
db.orders.aggregate([
// Filter by date
{
$match: {
createdAt: {
$gte: new Date("2026-01-01"),
$lt: new Date("2026-02-01"),
},
},
},
// Join with products
{
$lookup: {
from: "products",
localField: "productId",
foreignField: "_id",
as: "product",
},
},
// Unwind product array
{ $unwind: "$product" },
// Group by category
{
$group: {
_id: "$product.category",
totalRevenue: { $sum: "$amount" },
totalOrders: { $sum: 1 },
avgOrderValue: { $avg: "$amount" },
},
},
// Sort by revenue
{ $sort: { totalRevenue: -1 } },
// Format output
{
$project: {
category: "$_id",
totalRevenue: { $round: ["$totalRevenue", 2] },
totalOrders: 1,
avgOrderValue: { $round: ["$avgOrderValue", 2] },
_id: 0,
},
},
]);
Node.js Integration
Install Driver
npm install mongodb
Connection
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");
return client.db("mydb");
} catch (error) {
console.error("Connection error:", error);
throw error;
}
}
module.exports = { client, connect };
CRUD with Node.js
const { connect, client } = require("./db");
async function main() {
const db = await connect();
const users = db.collection("users");
// Insert
const result = await users.insertOne({
name: "Budi",
email: "budi@email.com",
});
console.log("Inserted ID:", result.insertedId);
// Find
const user = await users.findOne({ name: "Budi" });
console.log("Found:", user);
// Find many
const allUsers = await users.find({ age: { $gt: 20 } }).toArray();
console.log("All users:", allUsers);
// Update
await users.updateOne({ name: "Budi" }, { $set: { age: 26 } });
// Delete
await users.deleteOne({ name: "Budi" });
// Close connection
await client.close();
}
main().catch(console.error);
With Mongoose (ODM)
// npm install mongoose
const mongoose = require("mongoose");
// Connect
mongoose.connect("mongodb://localhost:27017/mydb");
// Define Schema
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 0 },
roles: [String],
createdAt: { type: Date, default: Date.now },
});
// Create Model
const User = mongoose.model("User", userSchema);
// CRUD Operations
async function example() {
// Create
const user = new User({
name: "Budi",
email: "budi@email.com",
age: 25,
});
await user.save();
// Find
const users = await User.find({ age: { $gt: 20 } });
const oneUser = await User.findOne({ email: "budi@email.com" });
// Update
await User.findByIdAndUpdate(user._id, { age: 26 });
// Delete
await User.findByIdAndDelete(user._id);
}
Data Modeling
Embedded Documents
// Good for: 1-to-few, frequently accessed together
{
_id: ObjectId("..."),
name: "Budi",
addresses: [
{ type: "home", city: "Jakarta" },
{ type: "work", city: "Bandung" }
],
orders: [
{ productId: "...", amount: 100000 },
{ productId: "...", amount: 200000 }
]
}
References
// Good for: 1-to-many, many-to-many, large documents
// User document
{
_id: ObjectId("user1"),
name: "Budi"
}
// Order documents (reference user)
{
_id: ObjectId("order1"),
userId: ObjectId("user1"),
amount: 100000
}
Kesimpulan
MongoDB adalah database NoSQL yang flexible untuk aplikasi modern. Pahami kapan menggunakan embedded vs references, dan optimize dengan indexes.
Ditulis oleh
Hendra Wijaya
Artikel Sebelumnya
Cara Menggunakan Majestic SEO untuk Backlink Analysis
Artikel Selanjutnya
Cara Menggunakan Moz Pro untuk SEO: Tutorial Lengkap