基本操作
适用于 MongoDB 6.x/7.x +
mongosh。在保留原有截图的同时,补充多文档事务、Schema 校验、时间序列/向量集合等 2025 年常用能力,帮助全栈工程师快速掌握核心命令。
数据库相关
查看已有的数据库
      
        show dbs
      
    shell

查看当前数据库
      
        db
      
    shell

创建或切换数据库
      
        // 若数据库不存在则自动创建
use <数据库名>
      
    shell

查看集合
      
        show collections
      
    shell

创建集合与查看信息
      
        // 显式创建集合,可指定校验规则或存储选项
db.createCollection('fruit', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['name'],
      properties: {
        name: { bsonType: 'string' },
        price: { bsonType: ['double', 'decimal'] }
      }
    }
  }
});
db.fruit.stats();      // 查看集合统计信息
db.getCollectionInfos();
      
    js
删除数据库
      
        db.dropDatabase();
      
    js
警告:不可逆。删除前务必确认备份并在正确的命名空间执行。
增删改查(CRUD)
插入
      
        // 单条
db.fruit.insertOne({ name: 'apple', weight: 320, tags: ['red'] });
// 多条
db.fruit.insertMany([
  { name: 'pear', weight: 400 },
  { name: 'mango', weight: 500 }
], { ordered: false });
// bulkWrite(6.0+)
db.fruit.bulkWrite([
  { insertOne: { document: { name: 'grape', weight: 120 } } },
  { updateOne: { filter: { name: 'apple' }, update: { $inc: { stock: 10 } } } },
  { deleteOne: { filter: { discontinued: true } } }
]);
      
    js


查询
      
        // 全量查询
db.fruit.find();
// 条件查询
db.fruit.find({ name: 'apple' });
// 多条件 and
db.fruit.find({ name: 'pear', weight: 400 });
// $and 写法
db.fruit.find({ $and: [{ name: 'pear' }, { weight: 400 }] });
// 多条件 or
db.fruit.find({ $or: [{ name: 'apple' }, { weight: 400 }] });
// 正则
db.fruit.find({ name: /^a/i });
// 指定字段(投影)
db.fruit.find({}, { _id: 0, name: 1, weight: 1 });
// 排序 + 分页
db.fruit.find().sort({ weight: -1 }).skip(10).limit(5);
      
    js






常用条件:
| 语义 | 写法 | 
|---|---|
| a 等于 1 | { a: 1 } | 
| a 不等于 1 | { a: { $ne: 1 } } | 
| a 大于 1 | { a: { $gt: 1 } } | 
| a 小于 1 | { a: { $lt: 1 } } | 
| a 在集合中 | { a: { $in: [1, 2, 3] } } | 
| a 字段不存在 | { a: { $exists: false } } | 
更新
      
        // 基础更新
db.fruit.updateOne({ name: 'apple' }, { $set: { weight: 330 } });
// pipeline 更新(5.0+)
db.fruit.updateOne(
  { name: 'apple' },
  [{ $set: { priceWithTax: { $multiply: ['$price', 1.06] } } }],
  { upsert: true }
);
// 数组操作
db.fruit.updateOne(
  { name: 'apple' },
  { $addToSet: { tags: { $each: ['fresh', 'organic'] } } }
);
      
    js
常见操作符:$set、$unset、$inc、$addToSet、$push/$each、$pull、$setOnInsert。
删除
      
        // 删除单条
db.fruit.deleteOne({ name: 'mango' });
// 删除多条
db.fruit.deleteMany({ weight: { $lt: 100 } });
      
    js
建议配合
writeConcern: { w: 'majority', j: true }或开启备份,确保数据可恢复。
事务与会话(MongoDB 4.0+)
      
        const session = db.getMongo().startSession();
const orders = session.getDatabase('shop').orders;
try {
  session.startTransaction({
    readConcern: { level: 'snapshot' },
    writeConcern: { w: 'majority' }
  });
  orders.updateOne({ _id: orderId }, { $set: { status: 'PAID' } });
  db.getSiblingDB('inventory').stock.updateOne({ sku }, { $inc: { quantity: -1 } });
  session.commitTransaction();
} catch (err) {
  session.abortTransaction();
  throw err;
} finally {
  session.endSession();
}
      
    js
事务适合金融、电商等需要跨集合一致性的场景,仍建议优先通过文档建模减少事务开销。
索引与性能
      
        // 单字段索引
db.fruit.createIndex({ name: 1 });
// 复合索引
db.fruit.createIndex({ weight: -1, name: 1 });
// 部分索引
db.fruit.createIndex({ status: 1 }, { partialFilterExpression: { active: true } });
// 6.0 Columnstore 索引(适合分析型查询)
db.sales.createIndex({ '$**': 'columnstore' });
      
    js
使用
db.fruit.explain().find(...)分析查询计划,配合Atlas Performance Advisor或mongostat抓取热点。
Schema 校验
      
        db.createCollection('users', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['email', 'createdAt'],
      properties: {
        email: { bsonType: 'string', pattern: '^.+@.+$' },
        createdAt: { bsonType: 'date' },
        roles: {
          bsonType: 'array',
          items: { enum: ['admin', 'editor', 'viewer'] }
        }
      }
    }
  },
  validationLevel: 'moderate'
});
      
    js
结合 changeStream 可实现实时审计。
时间序列与向量集合
      
        // 时间序列集合(IoT/监控)
db.createCollection('metrics', {
  timeseries: {
    timeField: 'timestamp',
    metaField: 'deviceId',
    granularity: 'seconds'
  }
});
// 向量索引(Atlas Vector Search / 7.0+ 社区版)
db.documents.createIndex({ embedding: 'vectorSearch' }, {
  similarity: 'cosine',
  dimensions: 1536
});
      
    js
向量查询示例:
      
        db.documents.aggregate([
  {
    $vectorSearch: {
      index: 'embedding-index',
      path: 'embedding',
      queryVector: queryEmbedding,
      numCandidates: 200,
      limit: 10
    }
  }
]);
      
    js
Change Stream(事件驱动)
      
        const cursor = db.collection.watch([
  { $match: { operationType: { $in: ['insert', 'update'] } } }
]);
while (cursor.hasNext()) {
  printjson(cursor.next());
}
      
    js
可结合 Node.js/Serverless 构建实时通知、缓存同步或 AI 工作流。
备份与恢复(简述)
mongodump/mongorestore:适合同步或迁移小型数据集mongoexport/mongoimport:与 CSV/JSON 互转- Atlas 提供 Continuous Backup、Point-in-Time Recovery(PITR)
 - 自建环境可使用 
oplog级别的增量备份或外部工具(Percona Backup for MongoDB) 
生产环境建议配置复制集 + 定期全量/增量备份,再配合自动化监控(Cloud Manager、Ops Manager 或 Prometheus Exporter)。
 ↑