MongoDB Basics

What is MongoDB?

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's designed for scalability, performance, and developer productivity.

Key Features

  • Document-oriented storage
  • Dynamic schemas
  • Horizontal scalability
  • High performance
  • Rich query language
  • Automatic sharding

Core Concepts

Documents

MongoDB stores data in BSON (Binary JSON) documents. Here's an example:

{
    "_id": ObjectId("..."),
    "name": "John Doe",
    "age": 30,
    "email": "john@example.com",
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "country": "USA"
    },
    "interests": ["reading", "music", "sports"]
}

Collections

Collections are groups of documents, similar to tables in relational databases.

// Create a collection
db.createCollection("users")

// Insert a document
db.users.insertOne({
    name: "John Doe",
    age: 30
})

Databases

MongoDB databases are containers for collections.

// Switch to a database
use myDatabase

// List all databases
show dbs

// List all collections
show collections

Basic Operations

Creating Documents

// Insert a single document
db.users.insertOne({
    name: "John Doe",
    age: 30
})

// Insert multiple documents
db.users.insertMany([
    { name: "Jane Doe", age: 25 },
    { name: "Bob Smith", age: 35 }
])

Reading Documents

// Find all documents
db.users.find()

// Find with a filter
db.users.find({ age: { $gt: 25 } })

// Find one document
db.users.findOne({ name: "John Doe" })

Next Steps

Now that you understand the basics of MongoDB, you can explore: