Node.js中操作MongoDB的CRUD操作指南

在Node.js中操作MongoDB常见的库有mongodb原生驱动和mongoose等。本文将使用mongodb官方驱动包来进行示例。在开始之前,请确保已经安装了MongoDB数据库并且在本地启动了MongoDB服务。

首先,需要安装mongodb驱动:

sh 复制代码
npm install mongodb

接着,可以创建一个连接到MongoDB的客户端:

javascript 复制代码
const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';  // MongoDB服务地址
const dbName = 'mydatabase';  // 数据库名称
const client = new MongoClient(url);

async function main() {
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    
    // 等待在这里执行CRUD操作

    client.close();
}

main().catch(console.error);

基础版

1. 创建(Create)

插入单条数据

javascript 复制代码
async function createDocument(collectionName, doc) {
    const collection = db.collection(collectionName);
    const result = await collection.insertOne(doc);
    console.log(result);
}

// 使用示例
createDocument('users', { name: 'Tom', age: 25 });

插入多条数据

javascript 复制代码
async function createMultipleDocuments(collectionName, docs) {
    const collection = db.collection(collectionName);
    const result = await collection.insertMany(docs);
    console.log(result);
}

// 使用示例
createMultipleDocuments('users', [
    { name: 'Alice', age: 23 },
    { name: 'Bob', age: 27 }
]);

2. 读取(Read)

查询单条数据

javascript 复制代码
async function findOneDocument(collectionName, query) {
    const collection = db.collection(collectionName);
    const doc = await collection.findOne(query);
    console.log(doc);
}

// 使用示例
findOneDocument('users', { name: 'Tom' });

查询多条数据

javascript 复制代码
async function findMultipleDocuments(collectionName, query) {
    const collection = db.collection(collectionName);
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

// 使用示例
findMultipleDocuments('users', { age: { $gt: 20 } });

3. 更新(Update)

更新单条数据

javascript 复制代码
async function updateOneDocument(collectionName, filter, updateDoc) {
    const collection = db.collection(collectionName);
    const result = await collection.updateOne(filter, { $set: updateDoc });
    console.log(result);
}

// 使用示例
updateOneDocument('users', { name: 'Tom' }, { age: 28 });

更新多条数据

javascript 复制代码
async function updateMultipleDocuments(collectionName, filter, updateDoc) {
    const collection = db.collection(collectionName);
    const result = await collection.updateMany(filter, { $set: updateDoc });
    console.log(result);
}

// 使用示例
updateMultipleDocuments('users', { age: { $lt: 30 } }, { active: true });

4. 删除(Delete)

删除单条数据

javascript 复制代码
async function deleteOneDocument(collectionName, query) {
    const collection = db.collection(collectionName);
    const result = await collection.deleteOne(query);
    console.log(result);
}

// 使用示例
deleteOneDocument('users', { name: 'Tom' });

删除多条数据

javascript 复制代码
async function deleteMultipleDocuments(collectionName, query) {
    const collection = db.collection(collectionName);
    const result = await collection.deleteMany(query);
    console.log(result);
}

// 使用示例
deleteMultipleDocuments('users', { active: true });

完成上面的操作后,确保关闭数据库连接。

javascript 复制代码
client.close();

在使用以上代码时,请通过替换collectionNamequeryupdateDoc的值以适配你的实际需求。

这个指南涵盖了在Node.js中使用MongoDB进行基本的CRUD操作的代码示例。在实际应用开发中,你可能需要根据实际业务逻辑对其进行更复杂的操作和封装。

在MongoDB中执行更高级的查询和修改操作通常涉及更复杂的查询条件、聚合操作以及对更新操作的细致控制。我将在此为您提供一些进阶使用示例。

进阶版

高级查询

查询时可以使用更复杂的操作符,比如$and, $or, $in, $not, $type, $regex等来构建复杂的查询语句。

使用逻辑运算符

javascript 复制代码
async function findWithLogicalOperators(collectionName) {
    const collection = db.collection(collectionName);
    // 查询年龄大于20并且名字以'A'开头的用户
    const query = { $and: [{ age: { $gt: 20 } }, { name: { $regex: /^A/ } }] };
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

findWithLogicalOperators('users');

使用数组查询

javascript 复制代码
async function findUsersWithSpecificInterests(collectionName) {
    const collection = db.collection(collectionName);
    // 查询兴趣中包含阅读的用户
    const query = { interests: "阅读" };
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

findUsersWithSpecificInterests('users');

使用聚合框架(Aggregation Framework)

MongoDB提供的聚合框架可以执行更复杂的数据处理任务,比如分组、排序、计算字段等。

分组和计算平均年龄

javascript 复制代码
async function averageAgeByInterest(collectionName) {
    const collection = db.collection(collectionName);
    const pipeline = [
        { $unwind: "$interests" },
        { $group: { _id: "$interests", averageAge: { $avg: "$age" } } },
        { $sort: { averageAge: -1 } }
    ];
    const result = await collection.aggregate(pipeline).toArray();
    console.log(result);
}

averageAgeByInterest('users');

高级更新

更新操作可以包括修改字段、添加新字段以及使用更新操作符如$inc, $push等。

更新并同时增加新字段

javascript 复制代码
async function updateAndAddField(collectionName, userId, incrementValue) {
    const collection = db.collection(collectionName);
    const filter = { _id: userId };
    const updateDoc = {
        $set: { lastActive: new Date() },
        $inc: { loginCount: incrementValue }
    };
    const result = await collection.updateOne(filter, updateDoc);
    console.log(result);
}

updateAndAddField('users', "someUserId", 1);

向数组中添加元素

javascript 复制代码
async function addInterestToUser(collectionName, userId, newInterest) {
    const collection = db.collection(collectionName);
    const filter = { _id: userId };
    const updateDoc = { $push: { interests: newInterest } };
    const result = await collection.updateOne(filter, updateDoc);
    console.log(result);
}

addInterestToUser('users', "someUserId", "游泳");

删除操作

删除操作同样可以是条件化的,你可以根据条件批量删除记录。

删除年龄在一定范围内的用户

javascript 复制代码
async function deleteUserByAgeRange(collectionName, minAge, maxAge) {
    const collection = db.collection(collectionName);
    const query = { age: { $gte: minAge, $lte: maxAge } };
    const result = await collection.deleteMany(query);
    console.log(result);
}

deleteUserByAgeRange('users', 18, 30);

English version

Guide to CRUD Operations with MongoDB in Node.js

In Node.js, common libraries for interacting with MongoDB include the native mongodb driver and mongoose, among others. Below, we will use the official mongodb driver package for demonstration. Before starting, please ensure MongoDB database is installed and the MongoDB service is running locally.

First, you need to install the mongodb driver:

sh 复制代码
npm install mongodb

Next, you can create a client to connect to MongoDB:

javascript 复制代码
const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';  // MongoDB service address
const dbName = 'mydatabase';  // Database name
const client = new MongoClient(url);

async function main() {
    await client.connect();
    console.log('Connected successfully to server');
    const db = client.db(dbName);
    
    // Perform CRUD operations here

    client.close();
}

main().catch(console.error);

1. Create

Inserting a Single Document

javascript 复制代码
async function createDocument(collectionName, doc) {
    const collection = db.collection(collectionName);
    const result = await collection.insertOne(doc);
    console.log(result);
}

// Usage example
createDocument('users', { name: 'Tom', age: 25 });

Inserting Multiple Documents

javascript 复制代码
async function createMultipleDocuments(collectionName, docs) {
    const collection = db.collection(collectionName);
    const result = await collection.insertMany(docs);
    console.log(result);
}

// Usage example
createMultipleDocuments('users', [
    { name: 'Alice', age: 23 },
    { name: 'Bob', age: 27 }
]);

2. Read

Querying a Single Document

javascript 复制代码
async function findOneDocument(collectionName, query) {
    const collection = db.collection(collectionName);
    const doc = await collection.findOne(query);
    console.log(doc);
}

// Usage example
findOneDocument('users', { name: 'Tom' });

Querying Multiple Documents

javascript 复制代码
async function findMultipleDocuments(collectionName, query) {
    const collection = db.collection(collectionName);
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

// Usage example
findMultipleDocuments('users', { age: { $gt: 20 } });

3. Update

Updating a Single Document

javascript 复制代码
async function updateOneDocument(collectionName, filter, updateDoc) {
    const collection = db.collection(collectionName);
    const result = await collection.updateOne(filter, { $set: updateDoc });
    console.log(result);
}

// Usage example
updateOneDocument('users', { name: 'Tom' }, { age: 28 });

Updating Multiple Documents

javascript 复制代码
async function updateMultipleDocuments(collectionName, filter, updateDoc) {
    const collection = db.collection(collectionName);
    const result = await collection.updateMany(filter, {

$set: updateDoc });
    console.log(result);
}

// Usage example
updateMultipleDocuments('users', { age: { $lt: 30 } }, { active: true });

4. Delete

Deleting a Single Document

javascript 复制代码
async function deleteOneDocument(collectionName, query) {
    const collection = db.collection(collectionName);
    const result = await collection.deleteOne(query);
    console.log(result);
}

// Usage example
deleteOneDocument('users', { name: 'Tom' });

Deleting Multiple Documents

javascript 复制代码
async function deleteMultipleDocuments(collectionName, query) {
    const collection = db.collection(collectionName);
    const result = await collection.deleteMany(query);
    console.log(result);
}

// Usage example
deleteMultipleDocuments('users', { active: true });

After completing the above operations, ensure to close the database connection.

javascript 复制代码
client.close();

When using the above code, please adapt it by replacing collectionName, query, and updateDoc with values that suit your actual needs.

This guide covers basic CRUD operation code examples using MongoDB in Node.js. In practical application development, you might need to perform more complex operations and encapsulations based on actual business logic.

Performing advanced queries and modifications in MongoDB often involves more complex query conditions, aggregation operations, and detailed control of update operations. Here are some advanced usage examples for you.

Advanced Queries

Queries can use more complex operators such as $and, $or, $in, $not, $type, $regex, etc., to build complex query statements.

Using Logical Operators

javascript 复制代码
async function findWithLogicalOperators(collectionName) {
    const collection = db.collection(collectionName);
    // Query users older than 20 and whose name starts with 'A'
    const query = { $and: [{ age: { $gt: 20 } }, { name: { $regex: /^A/ } }] };
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

findWithLogicalOperators('users');

Using Array Queries

javascript 复制代码
async function findUsersWithSpecificInterests(collectionName) {
    const collection = db.collection(collectionName);
    // Query users with interest in reading
    const query = { interests: "Reading" };
    const docs = await collection.find(query).toArray();
    console.log(docs);
}

findUsersWithSpecificInterests('users');

Using the Aggregation Framework

MongoDB's aggregation framework can perform more complex data processing tasks like grouping, sorting, computing fields, etc.

Grouping and Calculating Average Age

javascript 复制代码
async function averageAgeByInterest(collectionName) {
    const collection = db.collection(collectionName);
    const pipeline = [
        { $unwind: "$interests" },
        { $group: { _id: "$interests", averageAge: { $avg: "$age" } } },
        { $sort: { averageAge: -1 } }
    ];
    const result = await collection.aggregate(pipeline).toArray();
    console.log(result);
}

averageAgeByInterest('users');

Advanced Updates

Update operations can include modifying fields, adding new fields, and using update operators like $inc, $push, etc.

Updating and Adding a New Field

javascript 复制代码
async function updateAndAddField(collectionName, userId, incrementValue) {
    const collection = db.collection(collectionName);
    const filter = { _id: userId };
    const updateDoc = {
        $set: { lastActive: new Date() },
        $inc: { loginCount: incrementValue }
    };
    const result = await collection.updateOne(filter, updateDoc);
    console.log(result);
}

updateAndAddField('users', "someUserId

", 1);

Adding an Element to an Array

javascript 复制代码
async function addInterestToUser(collectionName, userId, newInterest) {
    const collection = db.collection(collectionName);
    const filter = { _id: userId };
    const updateDoc = { $push: { interests: newInterest } };
    const result = await collection.updateOne(filter, updateDoc);
    console.log(result);
}

addInterestToUser('users', "someUserId", "Swimming");

Delete Operations

Delete operations can also be conditional, allowing you to delete records in bulk based on certain conditions.

Deleting Users Within a Certain Age Range

javascript 复制代码
async function deleteUserByAgeRange(collectionName, minAge, maxAge) {
    const collection = db.collection(collectionName);
    const query = { age: { $gte: minAge, $lte: maxAge } };
    const result = await collection.deleteMany(query);
    console.log(result);
}

deleteUserByAgeRange('users', 18, 30);

The above are just a small part of MongoDB's advanced features. MongoDB has very powerful and flexible query and processing capabilities, and you can gain a more comprehensive understanding by reading MongoDB's official documentation. These advanced queries and update operations are very useful when your application needs to handle complex data models and advanced data operations.

相关推荐
梦帮科技4 小时前
Node.js配置生成器CLI工具开发实战
前端·人工智能·windows·前端框架·node.js·json
Misnice6 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
毕设源码-朱学姐1 天前
【开题答辩全过程】以 基于Node.js的书籍分享平台设计与实现为例,包含答辩的问题和答案
node.js
前端 贾公子1 天前
Node.js 如何处理 ES6 模块
前端·node.js·es6
周杰伦的稻香2 天前
Hexo搭建教程
java·node.js
毕设源码-钟学长2 天前
【开题答辩全过程】以 基于node.js vue的点餐系统的设计与实现为例,包含答辩的问题和答案
前端·vue.js·node.js
朝朝暮暮an2 天前
Day 2|Node.js 运行机制、模块系统与异步初探
node.js
aidou13142 天前
Visual Studio Code(VS Code)安装步骤
vscode·npm·node.js·环境变量
止观止2 天前
告别 require!TypeScript 5.9 与 Node.js 20+ 的 ESM 互操作指南
javascript·typescript·node.js
一只专注api接口开发的技术猿2 天前
淘宝商品详情API的流量控制与熔断机制:保障系统稳定性的后端设计
大数据·数据结构·数据库·架构·node.js