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.

相关推荐
会周易的程序员14 小时前
js-shm: 高性能 Node.js 共享内存模块
开发语言·javascript·c++·node.js·共享内存·shm
5G微创业18 小时前
Python / Node.js 调用短视频去水印 API 完整示例(含 SDK)
python·node.js·音视频·api·sdk·短视频
寒水馨19 小时前
macOS下载、安装electron-v43.2.0(附安装包electron-v43.2.0-darwin-arm64.zip)
javascript·macos·electron·node.js·跨平台·桌面应用开发·开源框架
hoLzwEge1 天前
拯救低效调试!code-inspector-plugin 让代码定位如虎添翼
前端·前端框架·node.js
无巧不成书02182 天前
Node.js 多版本管理完全教程:nvm 全平台安装、版本切换与新手避坑实战
node.js·nvm·全平台安装·避坑实战
无情的西瓜皮2 天前
给 AI 装个“工具箱”:MCP 协议入门与 Node.js 实战
人工智能·node.js
__zRainy__2 天前
Node.js readline 全景指南:createInterface 配置、逐行读取与交互模式
node.js·readline
To_OC2 天前
拼路径读文件总踩坑?我把 Node 的 path 和 fs 彻彻底底捋了一遍
javascript·后端·node.js
星栈2 天前
从装一堆工具到看懂 Node 工程化思维:我的项目复盘记录
后端·node.js
东方小月2 天前
从零开发一个Coding Agent:monorepo项目搭建
前端·后端·node.js