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.

相关推荐
你的人类朋友9 小时前
【Node&Vue】JS是编译型语言还是解释型语言?
javascript·node.js·编程语言
Orange30151113 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
Clownseven18 小时前
Docker+Nginx+Node.js实战教程:从零搭建高可用的前后端分离项目
nginx·docker·node.js
PineappleCoder1 天前
同源策略是啥?浏览器为啥拦我的跨域请求?(一)
前端·后端·node.js
stoneSkySpace1 天前
pnpm 和 npm 差异
前端·npm·node.js
你的人类朋友1 天前
【Node.js】什么是Node.js
javascript·后端·node.js
LKAI.1 天前
传统方式部署(RuoYi-Cloud)微服务
java·linux·前端·后端·微服务·node.js·ruoyi
Q_Q19632884752 天前
python的电影院座位管理可视化数据分析系统
开发语言·spring boot·python·django·flask·node.js·php
一枚前端小能手2 天前
⚡ Node.js服务器慢得像蜗牛,性能优化实战分享
前端·node.js·dnodejs
Cecilialana2 天前
在安装 node-sass 时出现的编译问题
webpack·node.js