Cheat Sheet速查表
跳转到主要内容

MongoDB 常用命令速查表

MongoDB 是主流的文档型 NoSQL 数据库。本速查表涵盖 Mongosh 终端交互、集合维护、CRUD 数据操作与聚合管道语法。

数据库与连接管理

命令说明
mongosh "mongodb://localhost:27017/mydb"连接到指定数据库
use mydb切换到指定数据库(不存在则自动创建)
db查看当前所在的数据库名
show dbs列出所有数据库列表
show collections列出当前数据库下的全部集合
exit退出客户端

集合操作 (DDL)

命令说明
db.createCollection("users")手动显式创建集合
db.users.drop()删除指定集合
db.users.stats()查看集合占用大小与统计信息
db.users.renameCollection("people")重命名集合

文档操作 (CRUD)

插入文档

// 插入单条与多条文档
db.users.insertOne({ name: "Alice", age: 25, role: "admin" });
db.users.insertMany([{ name: "Bob", age: 30 }, { name: "Charlie", age: 22 }]);

查询文档

// 格式化输出全部记录
db.users.find().pretty();

// 条件查询、排序与分页
db.users.find({ age: { $gt: 20 } }).sort({ age: 1 }).limit(10);

// 查询单条匹配记录
db.users.findOne({ name: "Alice" });

更新文档

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

// 批量条件更新
db.users.updateMany({ age: { $lt: 18 } }, { $set: { status: "minor" } });

删除文档

// 删除单条记录
db.users.deleteOne({ _id: ObjectId("60c72b2f9b1d8b2bad7d8b45") });

// 批量删除记录
db.users.deleteMany({ status: "inactive" });

常用查询与更新操作符

类型操作符说明
比较$gt, $gte, $lt, $lte, $ne, $in大于、大于等于、小于、小于等于、不等于、包含于数组
逻辑$and, $or, $not, $nor逻辑与、逻辑或、非、非或
字段$set, $unset, $inc, $rename设置属性、移除属性、数值自增、重命名字段
数组$push, $pop, $pull, $addToSet追加元素、出栈、移除匹配项、添加唯一元素

聚合管道 (Aggregation Pipeline)

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

索引管理

命令说明
db.users.createIndex({ name: 1 })为指定字段创建单字段升序索引
db.users.createIndex({ email: 1 }, { unique: true })创建唯一索引
db.users.getIndexes()查看集合上的全部索引
db.users.dropIndex("name_1")删除指定名称的索引