MongoDB Concepts — Database

Apa itu MongoDB? MongoDB adalah document database NoSQL yang menyimpan data dalam format BSON (Binary JSON). Tidak ada schema tetap — setiap dokumen bisa punya

Apa itu MongoDB?

MongoDB adalah document database NoSQL yang menyimpan data dalam format BSON (Binary JSON). Tidak ada schema tetap — setiap dokumen bisa punya struktur berbeda.

Konsep Dasar

CRUD Operations

// Create
db.users.insertOne({
    name: "Budi",
    email: "[email protected]",
    age: 25,
    hobbies: ["coding", "gaming"]
});

// Read
db.users.find({ age: { $gt: 20 } });           // age > 20
db.users.findOne({ email: "[email protected]" });

// Update
db.users.updateOne(
    { email: "[email protected]" },
    { $set: { age: 26 }, $push: { hobbies: "reading" } }
);

// Delete
db.users.deleteOne({ email: "[email protected]" });

Embedding vs Referencing

// Embedding: data terkait disimpan dalam satu dokumen
// ✅ Cocok untuk data yang selalu diakses bersama
{
    "name": "Budi",
    "address": {
        "street": "Jl. Merdeka 1",
        "city": "Jakarta"
    }
}

// Referencing: simpan ID referensi (seperti foreign key)
// ✅ Cocok untuk data yang bisa berdiri sendiri
{
    "title": "Tutorial MongoDB",
    "author_id": ObjectId("507f1f77bcf86cd799439011")
}

Index di MongoDB

// Single field index
db.users.createIndex({ email: 1 });

// Compound index
db.orders.createIndex({ user_id: 1, created_at: -1 });

// Text index (full-text search)
db.articles.createIndex({ title: "text", body: "text" });

Kapan MongoDB?

Yang akan kamu pelajari