MongoDB 备忘单

基本操作

  • mongo - 启动MongoDB shell
  • show dbs - 显示所有数据库
  • use [数据库名] - 切换到指定数据库(不存在则创建)
  • db - 显示当前数据库
  • db.dropDatabase() - 删除当前数据库
  • show collections - 显示当前数据库中的集合

集合操作

  • db.createCollection("collectionName") - 创建集合
  • db.collectionName.drop() - 删除集合
  • db.collectionName.renameCollection("newName") - 重命名集合

文档插入

// 插入单个文档 db.users.insertOne({ name: "John Doe", email: "john@example.com", age: 30, hobbies: ["reading", "sports"], created_at: new Date() }); // 插入多个文档 db.users.insertMany([ { name: "Jane Smith", email: "jane@example.com", age: 25 }, { name: "Bob Johnson", email: "bob@example.com", age: 35 } ]);

文档查询

// 查询所有文档 db.users.find(); // 格式化输出 db.users.find().pretty(); // 条件查询 db.users.find({ age: 30 }); // 等于 db.users.find({ age: { $gt: 25 } }); // 大于 db.users.find({ age: { $lt: 30 } }); // 小于 db.users.find({ age: { $gte: 25, $lte: 35 } }); // 范围 // 逻辑查询 db.users.find({ $or: [{ age: 25 }, { age: 35 }] }); // 投影(只返回指定字段) db.users.find({}, { name: 1, email: 1, _id: 0 }); // 排序 db.users.find().sort({ age: 1 }); // 升序 db.users.find().sort({ age: -1 }); // 降序 // 限制结果 db.users.find().limit(5); // 跳过结果 db.users.find().skip(5);

文档更新与删除

// 更新单个文档 db.users.updateOne( { name: "John Doe" }, { $set: { age: 31, email: "john.new@example.com" } } ); // 更新多个文档 db.users.updateMany( { age: { $lt: 18 } }, { $set: { status: "minor" } } ); // 替换文档 db.users.replaceOne( { name: "John Doe" }, { name: "John Doe", email: "john.updated@example.com", age: 31 } ); // 删除单个文档 db.users.deleteOne({ name: "John Doe" }); // 删除多个文档 db.users.deleteMany({ age: { $lt: 18 } });