MongoDB Essentials: NoSQL Database for Modern Applications

MongoDB is a document-oriented NoSQL database. It stores data in flexible JSON-like documents, making it ideal for modern applications.

## Key Concepts

- **Database**: Container for collections
- **Collection**: Group of documents (like tables)
- **Document**: JSON-like record (like rows)
- **Field**: Key-value pair (like columns)

## Basic Operations

```javascript
// Insert
db.users.insertOne({ name: "John", age: 30 })
db.users.insertMany([{ name: "Jane" }, { name: "Bob" }])

// Query
db.users.find({ age: { $gt: 25 } })
db.users.findOne({ name: "John" })

// Update
db.users.updateOne(
 { name: "John" },
 { $set: { age: 31 } }
)

// Delete
db.users.deleteOne({ name: "John" })
```

## Query Operators

```javascript
// Comparison
{ age: { $gt: 25 } }  // Greater than
{ age: { $lt: 25 } }  // Less than
{ age: { $gte: 25 } } // Greater or equal
{ age: { $in: [25, 30, 35] } }  // In array

// Logical
{ $and: [{ age: { $gt: 20 } }, { age: { $lt: 30 } }] }
{ $or: [{ status: "active" }, { status: "pending" }] }
```

## Indexing

```javascript
// Create index
db.users.createIndex({ email: 1 })  // Ascending
db.users.createIndex({ name: 1, age: -1 })  // Compound

// List indexes
db.users.getIndexes()
```

## Aggregation

```javascript
db.orders.aggregate([
 { $match: { status: "completed" } },
 { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
 { $sort: { total: -1 } }
])
```

## Schema Design

- Embed related data for fast reads
- Reference for large/repeated data
- Use arrays for one-to-many

## Conclusion

MongoDB's flexible schema and powerful query language make it perfect for rapid development and scalable applications.

评论
暂无评论