MongoDB 数据库基本操作指南

4 阅读1分钟

连接 MongoDB

使用 MongoDB 的官方驱动或客户端工具连接数据库。以下是使用 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 (err) {
        console.error('Connection error:', err);
    }
}
connect();

创建数据库和集合

MongoDB 无需显式创建数据库或集合,插入数据时会自动创建。以下示例创建一个名为 mydb 的数据库和 users 集合:

const db = client.db('mydb');
const users = db.collection('users');

插入文档

使用 insertOneinsertMany 插入数据:

// 插入单条文档
await users.insertOne({ name: 'Alice', age: 25 });

// 插入多条文档
await users.insertMany([
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 35 }
]);

查询文档

使用 find 方法查询数据,支持条件过滤和投影:

// 查询所有文档
const allUsers = await users.find().toArray();

// 条件查询(年龄大于 30)
const filteredUsers = await users.find({ age: { $gt: 30 } }).toArray();

// 投影(仅返回 name 字段)
const namesOnly = await users.find({}, { projection: { name: 1 } }).toArray();

更新文档

使用 updateOneupdateMany 更新数据:

// 更新单条文档(将 Alice 的年龄改为 26)
await users.updateOne({ name: 'Alice' }, { $set: { age: 26 } });

// 更新多条文档(将所有年龄大于 30 的用户标记为 senior)
await users.updateMany({ age: { $gt: 30 } }, { $set: { status: 'senior' } });

删除文档

使用 deleteOnedeleteMany 删除数据:

// 删除单条文档(删除名为 Bob 的记录)
await users.deleteOne({ name: 'Bob' });

// 删除多条文档(删除所有年龄小于 25 的记录)
await users.deleteMany({ age: { $lt: 25 } });

索引操作

索引可加速查询,以下是创建和删除索引的示例:

// 创建单字段索引(对 name 字段升序索引)
await users.createIndex({ name: 1 });

// 创建复合索引(对 name 和 age 字段)
await users.createIndex({ name: 1, age: 1 });

// 删除索引
await users.dropIndex('name_1');

聚合操作

使用聚合管道进行复杂数据处理:

const pipeline = [
    { $match: { age: { $gt: 25 } } }, // 过滤年龄大于 25
    { $group: { _id: '$name', total: { $sum: 1 } } } // 按名称分组计数
];
const result = await users.aggregate(pipeline).toArray();

关闭连接

操作完成后关闭数据库连接:

async function close() {
    await client.close();
    console.log('Connection closed');
}
close();