插件窝 干货文章 mongodb数据库怎么增删改查

mongodb数据库怎么增删改查

collection const await javascript 966    来源:    2025-03-27

MongoDB 数据库增删改查操作指南

MongoDB 是一个基于文档的 NoSQL 数据库,以下是基本的增删改查(CRUD)操作说明。

1. 连接数据库

// 使用 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());

2. 插入文档(Create)

插入单个文档

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);

3. 查询文档(Read)

查询所有文档

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();

4. 更新文档(Update)

更新单个文档

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);

5. 删除文档(Delete)

删除单个文档

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);

6. 索引操作

创建索引

// 创建单字段索引
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的索引

7. 聚合操作

const aggregationResult = await collection.aggregate([
  { $match: { age: { $gt: 25 } } }, // 筛选
  { $group: { _id: "$name", total: { $sum: 1 } } }, // 分组
  { $sort: { total: -1 } } // 排序
]).toArray();
console.log('Aggregation result:', aggregationResult);

8. 事务操作

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 基本的增删改查操作。根据实际需求,可以结合不同的查询操作符、更新操作符和聚合管道来实现更复杂的数据操作。