MongoDB - 速查表
MongoDB 现代速查表
Section titled “MongoDB 现代速查表”本速查表提供了基本 MongoDB 命令和概念的快速参考,并已针对现代开发实践进行了更新。MongoDB 是一种领先的 NoSQL 文档型数据库,非常适合可扩展和灵活的 Web 应用程序。
1. 安装与设置
Section titled “1. 安装与设置”通过包管理器安装 MongoDB Community Edition,或使用 Docker 进行可移植设置。
# macOS (使用 Homebrew)brew tap mongodb/brewbrew install mongodb-community
# Ubuntu (使用 apt)wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.listsudo apt-get updatesudo apt-get install -y mongodb-org
# Docker (推荐用于开发)docker run -d -p 27017:27017 --name my-mongo mongo使用 MongoDB Shell (mongosh) 连接:
mongosh2. 数据库和集合命令
Section titled “2. 数据库和集合命令”- 切换/创建数据库:
use myNewDB(数据库在首次插入数据时创建) - 显示当前数据库:
db - 列出所有数据库:
show dbs - 创建集合(显式):
db.createCollection("users") - 显示集合:
show collections - 删除当前数据库:
db.dropDatabase() - 删除集合:
db.users.drop()
3. CRUD 操作
Section titled “3. CRUD 操作”创建(插入)
Section titled “创建(插入)”// 插入单个文档db.users.insertOne({ name: "Alice", age: 30, city: "New York" })
// 插入多个文档db.users.insertMany([ { name: "Bob", age: 25, city: "Paris" }, { name: "Charlie", age: 35, city: "Tokyo" }])读取(查找)
Section titled “读取(查找)”// 查找所有文档db.users.find()
// 带过滤条件的查找db.users.find({ city: "New York" })
// 查找单个文档db.users.findOne({ name: "Alice" })// 更新第一个匹配的文档db.users.updateOne( { name: "Alice" }, { $set: { age: 31 }, $currentDate: { lastModified: true } } // $set 设置字段值, $currentDate 设置当前日期)
// 更新所有匹配的文档db.users.updateMany( { city: "New York" }, { $inc: { bonusPoints: 10 } } // $inc 增加字段值)
// 替换文档db.users.replaceOne({ name: "Bob" }, { name: "Robert", age: 25, city: "Paris" })// 删除第一个匹配的文档db.users.deleteOne({ name: "Charlie" })
// 删除所有匹配的文档db.users.deleteMany({ age: { $lt: 20 } }) // $lt 小于4. 查询操作符
Section titled “4. 查询操作符”- 比较操作符:
$eq(等于),$ne(不等于),$gt(大于),$gte(大于等于),$lt(小于),$lte(小于等于),$in(在数组中),$nin(不在数组中) - 逻辑操作符:
$and,$or,$not,$nor - 元素操作符:
$exists(字段存在),$type(字段是某种 BSON 类型) - 数组操作符:
$all(匹配所有元素),$size(数组具有特定大小),$elemMatch(匹配数组中的元素)
// 查找年龄大于 30 岁 或 来自东京的用户db.users.find({ $or: [ { age: { $gt: 30 } }, { city: "Tokyo" } ] }) // $or 或, $gt 大于
// 查找具有 'zipcode' 字段的用户db.users.find({ zipcode: { $exists: true } }) // $exists 存在5. 查询游标
Section titled “5. 查询游标”修改 find() 查询的输出。
// 按年龄降序排序,限制 5 个结果,跳过前 2 个db.users.find().sort({ age: -1 }).limit(5).skip(2)
// 统计匹配查询的文档数量db.users.countDocuments({ city: "Paris" })
// 获取字段的非重复值db.users.distinct("city")// 创建单字段索引(升序)db.users.createIndex({ name: 1 })
// 创建复合索引db.users.createIndex({ city: 1, age: -1 })
// 创建唯一索引db.users.createIndex({ email: 1 }, { unique: true })
// 为文本搜索创建文本索引db.articles.createIndex({ content: "text" })
// 列出集合上的所有索引db.users.getIndexes()
// 删除特定索引db.users.dropIndex("name_1")7. 聚合框架
Section titled “7. 聚合框架”处理数据记录并返回计算结果。它是一个阶段管道。
// 按城市分组用户并计算每个城市的平均年龄db.users.aggregate([ { $match: { age: { $gte: 20 } } }, // 阶段 1: 过滤文档 { $group: { // 阶段 2: 按城市分组 _id: "$city", averageAge: { $avg: "$age" }, // $avg 平均值 userCount: { $sum: 1 } // $sum 求和 } }, { $sort: { userCount: -1 } } // 阶段 3: 按数量排序])8. 高级主题
Section titled “8. 高级主题”- 事务 (Transactions): 用于多文档 ACID 事务。需要副本集。
- 变更流 (Change Streams): 实时数据更改流(插入、更新、删除)。
- 查询分析 (Query Analysis):
db.collection.explain('executionStats')查看查询性能。 - MongoDB Atlas: 官方云托管 MongoDB 服务,简化部署、扩展和管理。
// 事务示例const session = db.getMongo().startSession(); // 启动会话session.startTransaction(); // 启动事务const users = session.getDatabase("myDB").getCollection("users"); // 获取数据库和集合const audit = session.getDatabase("myDB").getCollection("audit");
users.updateOne({ name: "Alice" }, { $inc: { balance: -100 } });audit.insertOne({ user: "Alice", action: "debit", amount: 100 });
session.commitTransaction(); // 提交事务session.endSession(); // 结束会话