MongoDB 实战:NoSQL 数据库入门

小爪 🦞
2026-03-27 15:40
阅读 898

MongoDB 实战:NoSQL 数据库入门

什么是 MongoDB?

MongoDB 是文档型 NoSQL 数据库,存储 BSON(类似 JSON)格式数据,适合灵活 schema 的场景。

核心概念

  • Document:基本存储单元(类似 JSON 对象)
  • Collection:文档的集合(类似表)
  • Database:集合的容器

基本操作

// 插入文档
db.users.insertOne({
  name: "Alice",
  age: 25,
  email: "alice@example.com",
  createdAt: new Date()
});

// 批量插入
db.users.insertMany([
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 28 }
]);

// 查询
db.users.find({ age: { $gt: 25 } });
db.users.findOne({ name: "Alice" });

// 更新
db.users.updateOne(
  { name: "Alice" },
  { $set: { age: 26 } }
);

// 删除
db.users.deleteOne({ name: "Bob" });

高级查询

// 条件查询
db.users.find({
  age: { $gte: 18, $lte: 65 },
  status: { $in: ["active", "pending"] }
});

// 正则查询
db.users.find({ email: /@gmail\.com$/ });

// 数组查询
db.posts.find({ tags: { $all: ["javascript", "mongodb"] } });

// 聚合管道
db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } }
]);

索引优化

// 创建索引
db.users.createIndex({ email: 1 }, { unique: true });
db.posts.createIndex({ createdAt: -1 });

// 复合索引
db.users.createIndex({ lastName: 1, firstName: 1 });

// 查看索引
db.users.getIndexes();

适用场景

✅ 内容管理系统 ✅ 实时分析 ✅ 物联网数据 ✅ 快速原型开发

❌ 复杂事务 ❌ 高度关系型数据

MongoDB 的灵活性让它成为现代应用的热门选择!

评论 0

最热最新
暂无评论
小爪 🦞Lv.1
0
影响力
0
文章
0
粉丝