MongoDB是一种开源的NoSQL数据库,使用文档型存储数据格式(类似于JSON的BSON格式),以解决传统关系型数据库在处理大数据和高并发场景中的局限性。
MongoDB的特点
- 文档存储:使用类似JSON的BSON格式存储数据。
- 灵活的模式:无需预定义表结构,支持动态模式。
- 高可用性:通过副本集实现数据的冗余和自动故障恢复。
- 水平扩展:通过分片技术实现数据分布到多个节点。
- 强大的查询能力:支持丰富的查询语法和聚合功能。
安装与配置
1. 安装 MongoDB
可以通过包管理器或者下载压缩包的方式安装MongoDB。在Ubuntu上,可以使用以下命令安装:
bash
sudo apt-get update
sudo apt-get install -y mongodb
2. 启动和停止 MongoDB
启动MongoDB服务:
bash
sudo service mongodb start
停止MongoDB服务:
bash
sudo service mongodb stop
基本操作示例
1. 创建数据库和集合
javascript
// 连接 MongoDB
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
async function run() {
try {
await client.connect();
console.log("Connected to MongoDB");
const db = client.db('mydatabase'); // 创建或选择数据库
const collection = db.collection('users'); // 创建或选择集合
// 插入文档
const insertResult = await collection.insertOne({ name: "John Doe", email: "john.doe@example.com" });
console.log('Inserted document:', insertResult.ops[0]);
// 查询文档
const user = await collection.findOne({ name: "John Doe" });
console.log('Found document:', user);
// 更新文档
const updateResult = await collection.updateOne({ name: "John Doe" }, { $set: { email: "john.doe@newdomain.com" } });
console.log('Updated document count:', updateResult.modifiedCount);
// 删除文档
const deleteResult = await collection.deleteOne({ name: "John Doe" });
console.log('Deleted document count:', deleteResult.deletedCount);
} finally {
await client.close();
}
}
run().catch(console.dir);
2. 使用索引
索引对于提高查询性能非常重要。以下示例展示如何创建索引:
javascript
async function createIndex() {
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db('mydatabase');
const collection = db.collection('users');
// 创建索引
const indexName = await collection.createIndex({ email: 1 });
console.log('Created index:', indexName);
// 查询使用索引
const user = await collection.findOne({ email: "john.doe@newdomain.com" });
console.log('Found document using index:', user);
} finally {
await client.close();
}
}
createIndex().catch(console.dir);
3. 聚合操作
聚合操作用于处理数据并返回计算结果。以下示例展示如何进行聚合操作:
javascript
async function aggregationExample() {
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db('mydatabase');
const collection = db.collection('orders');
// 插入多个文档
await collection.insertMany([
{ product: "Apple", quantity: 10, price: 2.5 },
{ product: "Banana", quantity: 5, price: 1.2 },
{ product: "Orange", quantity: 8, price: 3.0 }
]);
// 使用聚合管道计算总销售额
const aggregationPipeline = [
{ $group: { _id: null, total: { $sum: { $multiply: ["$quantity", "$price"] } } } }
];
const aggResult = await collection.aggregate(aggregationPipeline).toArray();
console.log('Total sales:', aggResult[0].total);
} finally {
await client.close();
}
}
aggregationExample().catch(console.dir);
高级功能
副本集
副本集(Replica Set)是MongoDB高可用性的实现方式。它由一个主节点(Primary Node)和多个从节点(Secondary Nodes)组成。
要配置副本集,需要在配置文件中添加以下内容:
yaml
replication:
replSetName: "rs0"
然后启动MongoDB实例并初始化副本集:
javascript
rs.initiate()
分片
分片(Sharding)用于处理大量数据,将数据分布在多个服务器上。以下是分片的基本步骤:
javascript
// 启用分片
sh.enableSharding("mydatabase")
// 为集合设置分片键
sh.shardCollection("mydatabase.users", { "_id": 1 })
总结
MongoDB是一种灵活、可扩展的NoSQL数据库,适用于处理大规模数据和高并发应用。通过丰富的API和各种高级特性,如副本集和分片,MongoDB提供了强大的数据存储和管理能力。上述示例展示了MongoDB的基本操作、索引使用、聚合操作以及高级功能的配置,是理解和掌握MongoDB的良好起点。