MongoDB 是一个基于文档的 NoSQL 数据库,以下是基本的增删改查(CRUD)操作说明。
// 使用 MongoDB Node.js 驱动
const { MongoClient } = require('mongodb');
// 连接URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// 数据库名
const dbName = 'myDatabase';
async function main() {
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
// 在这里执行CRUD操作
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
const collection = db.collection('users');
const insertResult = await collection.insertOne({
name: '张三',
age: 25,
email: 'zhangsan@example.com',
hobbies: ['游泳', '阅读']
});
console.log('Inserted document:', insertResult.insertedId);
const insertManyResult = await collection.insertMany([
{ name: '李四', age: 30, email: 'lisi@example.com' },
{ name: '王五', age: 28, email: 'wangwu@example.com' }
]);
console.log('Inserted documents:', insertManyResult.insertedCount);
const findResult = await collection.find({}).toArray();
console.log('Found documents:', findResult);
// 查询年龄大于25的用户
const filteredDocs = await collection.find({ age: { $gt: 25 } }).toArray();
console.log('Found documents with age > 25:', filteredDocs);
// 查询指定名字的用户
const specificUser = await collection.findOne({ name: '张三' });
console.log('Found user:', specificUser);
// 使用多个条件
const complexQuery = await collection.find({
age: { $gte: 25, $lte: 30 },
name: { $regex: /张/ }
}).toArray();
// 限制返回字段
const projectionQuery = await collection.find(
{ age: { $gt: 25 } },
{ projection: { name: 1, email: 1 } }
).toArray();
const updateResult = await collection.updateOne(
{ name: '张三' },
{ $set: { age: 26 } }
);
console.log('Updated documents:', updateResult.modifiedCount);
const updateManyResult = await collection.updateMany(
{ age: { $gt: 25 } },
{ $inc: { age: 1 } } // 年龄加1
);
console.log('Updated documents:', updateManyResult.modifiedCount);
const replaceResult = await collection.replaceOne(
{ name: '李四' },
{ name: '李四', age: 31, email: 'new_lisi@example.com', status: 'active' }
);
console.log('Replaced document:', replaceResult.modifiedCount);
const deleteResult = await collection.deleteOne({ name: '王五' });
console.log('Deleted documents:', deleteResult.deletedCount);
const deleteManyResult = await collection.deleteMany({ age: { $gt: 30 } });
console.log('Deleted documents:', deleteManyResult.deletedCount);
// 创建单字段索引
await collection.createIndex({ name: 1 }); // 1表示升序,-1表示降序
// 创建复合索引
await collection.createIndex({ name: 1, age: -1 });
// 创建唯一索引
await collection.createIndex({ email: 1 }, { unique: true });
const indexes = await collection.indexes();
console.log('Collection indexes:', indexes);
await collection.dropIndex('name_1'); // 删除名为name_1的索引
const aggregationResult = await collection.aggregate([
{ $match: { age: { $gt: 25 } } }, // 筛选
{ $group: { _id: "$name", total: { $sum: 1 } } }, // 分组
{ $sort: { total: -1 } } // 排序
]).toArray();
console.log('Aggregation result:', aggregationResult);
const session = client.startSession();
try {
await session.withTransaction(async () => {
const usersCollection = db.collection('users');
const accountsCollection = db.collection('accounts');
await usersCollection.insertOne(
{ name: '赵六', age: 35 },
{ session }
);
await accountsCollection.insertOne(
{ username: 'zhaoliu', balance: 1000 },
{ session }
);
});
} finally {
await session.endSession();
}
以上是 MongoDB 基本的增删改查操作。根据实际需求,可以结合不同的查询操作符、更新操作符和聚合管道来实现更复杂的数据操作。