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.

相关推荐
百***78452 小时前
node.js+npm的环境配置以及添加镜像(保姆级教程)
arcgis·npm·node.js
百***07183 小时前
Node.js 与 Docker 深度整合:轻松部署与管理 Node.js 应用
docker·容器·node.js
菠萝+冰3 小时前
npm中-d -g 和默认安装的区别
前端·npm·node.js
夏日不想说话5 小时前
一文搞懂 AI 流式响应
前端·node.js·openai
百***67035 小时前
Node.js实现WebSocket教程
websocket·网络协议·node.js
q***51896 小时前
如何在Windows系统上安装和配置Node.js及Node版本管理器(nvm)
windows·node.js
天天进步20158 小时前
Webpack到Vite:构建工具迁移实战经验总结
前端·webpack·node.js
好奇的菜鸟8 小时前
解决 Node.js 18+ 构建错误:digital envelope routines::unsupported 完全指南
node.js
岁月宁静20 小时前
AI 多模态全栈应用项目描述
前端·vue.js·node.js
格鸰爱童话21 小时前
next.js学习——react入门
学习·react.js·node.js