MongoDB 基础入门
什么是 MongoDB?
MongoDB 是一个基于文档的 NoSQL 数据库,使用 JSON 格式存储数据,具有高性能、高可用性和易扩展的特点。
核心特性
- 文档数据库:以 BSON(Binary JSON)格式存储数据
- 无模式:不需要预定义表结构
- 水平扩展:支持分片和副本集
- 丰富的查询语言:支持复杂的查询操作
安装 MongoDB
Windows
- 访问 MongoDB 官网 下载安装包
- 运行安装程序,选择 "Complete" 安装
- 配置 MongoDB 服务
macOS
bash
# 使用 Homebrew
brew tap mongodb/brew
brew install mongodb-communityLinux
bash
# Ubuntu/Debian
sudo apt-get install -y mongodb
# 启动服务
sudo systemctl start mongodb
sudo systemctl enable mongodb基本概念
数据库(Database)
MongoDB 中可以创建多个数据库,每个数据库包含多个集合。
集合(Collection)
类似于关系型数据库中的表,但不需要预定义结构。
文档(Document)
类似于关系型数据库中的行,以 BSON 格式存储。
字段(Field)
文档中的键值对,类似于关系型数据库中的列。
基本操作
连接 MongoDB
javascript
// 使用 Node.js 连接
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri);
async function connect() {
try {
await client.connect();
console.log('Connected to MongoDB');
} catch (error) {
console.error('Connection error:', error);
}
}
connect();创建数据库和集合
javascript
const db = client.db('mydb');
const collection = db.collection('users');插入文档
javascript
// 插入单个文档
const result = await collection.insertOne({
name: 'John',
age: 30,
email: 'john@example.com'
});
// 插入多个文档
const result = await collection.insertMany([
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 35 }
]);查询文档
javascript
// 查询所有文档
const allUsers = await collection.find({}).toArray();
// 查询单个文档
const user = await collection.findOne({ name: 'John' });
// 条件查询
const users = await collection.find({ age: { $gt: 25 } }).toArray();
// 限制结果数量
const users = await collection.find({}).limit(10).toArray();更新文档
javascript
// 更新单个文档
await collection.updateOne(
{ name: 'John' },
{ $set: { age: 31 } }
);
// 更新多个文档
await collection.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: 'young' } }
);
// 替换文档
await collection.replaceOne(
{ name: 'John' },
{ name: 'John', age: 31, email: 'john@example.com' }
);删除文档
javascript
// 删除单个文档
await collection.deleteOne({ name: 'John' });
// 删除多个文档
await collection.deleteMany({ age: { $lt: 18 } });查询操作符
比较操作符
javascript
// $gt: 大于
{ age: { $gt: 25 } }
// $gte: 大于等于
{ age: { $gte: 25 } }
// $lt: 小于
{ age: { $lt: 30 } }
// $lte: 小于等于
{ age: { $lte: 30 } }
// $ne: 不等于
{ status: { $ne: 'deleted' } }
// $in: 在数组中
{ age: { $in: [25, 30, 35] } }
// $nin: 不在数组中
{ age: { $nin: [25, 30, 35] } }逻辑操作符
javascript
// $and: 与
{ $and: [{ age: { $gt: 25 } }, { status: 'active' }] }
// $or: 或
{ $or: [{ age: { $lt: 18 } }, { age: { $gt: 65 } }] }
// $not: 非
{ age: { $not: { $gt: 25 } } }
// $nor: 或非
{ $nor: [{ age: { $lt: 18 } }, { status: 'inactive' }] }数组操作符
javascript
// $all: 包含所有元素
{ tags: { $all: ['javascript', 'nodejs'] } }
// $size: 数组大小
{ tags: { $size: 3 } }
// $elemMatch: 匹配数组元素
{ scores: { $elemMatch: { $gt: 80, $lt: 90 } } }索引
创建索引
javascript
// 创建单字段索引
await collection.createIndex({ name: 1 });
// 创建复合索引
await collection.createIndex({ name: 1, age: -1 });
// 创建唯一索引
await collection.createIndex({ email: 1 }, { unique: true });查看索引
javascript
const indexes = await collection.indexes();
console.log(indexes);删除索引
javascript
await collection.dropIndex('name_1');聚合操作
javascript
// 聚合管道
const pipeline = [
{ $match: { status: 'active' } },
{ $group: { _id: '$category', total: { $sum: '$price' } } },
{ $sort: { total: -1 } }
];
const result = await collection.aggregate(pipeline).toArray();最佳实践
- 使用索引:为常用查询字段创建索引
- 避免深嵌套:文档结构不要过深
- 合理使用集合:根据数据关系设计集合结构
- 数据验证:使用 Schema 验证数据格式
- 连接池:合理配置连接池大小
最后更新:2025年