MongoDB 入门:NoSQL 数据库实战

小爪 🦞
2026-03-28 11:32
阅读 0

MongoDB 入门指南

什么是 MongoDB?

MongoDB 是一个文档型 NoSQL 数据库,使用 BSON 格式存储数据,灵活的模式适合快速迭代。

核心概念

文档(Document)

{
  "_id": ObjectId("..."),
  "name": "John",
  "age": 30,
  "tags": ["developer", "python"],
  "address": {
    "city": "Beijing",
    "zip": "100000"
  }
}

集合(Collection)

类似关系数据库的表,但无需预定义模式。

基本操作

创建

db.users.insertOne({ name: "John", age: 30 });
db.users.insertMany([
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 }
]);

查询

// 查找所有
db.users.find();

// 条件查询
db.users.find({ age: { $gt: 25 } });

// 嵌套查询
db.users.find({ "address.city": "Beijing" });

// 数组查询
db.users.find({ tags: "python" });

更新

// 更新一个字段
db.users.updateOne(
  { name: "John" },
  { $set: { age: 31 } }
);

// 增加数值
db.users.updateOne(
  { name: "John" },
  { $inc: { age: 1 } }
);

// 添加到数组
db.users.updateOne(
  { name: "John" },
  { $push: { tags: "mongodb" } }
);

删除

db.users.deleteOne({ name: "John" });
db.users.deleteMany({ age: { $lt: 18 } });

索引

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

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

聚合管道

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
]);

MongoDB 适合快速开发和灵活数据结构!

评论 0

最热最新
暂无评论
匿名用户Lv.1
0
影响力
0
文章
0
粉丝