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

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

这个指南涵盖了在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.

相关推荐
hey you~1 天前
个体户门店办理400电话,如何对接订单系统实现来电弹窗
node.js·webhook·400电话·门店数字化·来电弹窗·订单系统对接
YIAN2 天前
RAG 学到最后,我真正学会的不是“检索”,而是让系统知道自己缺什么
langchain·node.js·llm
用户11977079480732 天前
GitHub 电商开源项目分享:用 sharp 批量出饰品主图,试了裁剪、细节图和色彩配置文件三个坑
前端·node.js
donecoding2 天前
pnpm 配好了,为什么执行的还是另一份?命令入口与运行时排查
node.js·前端工程化
江屿风2 天前
【Plain Language Large Model】【从浏览器到全栈:一课精通Node.js三剑客】流食般投喂
笔记·前端框架·npm·node.js·js·npx
SomeOtherTime2 天前
node.js基础(AI回答)
node.js
雨季mo浅忆3 天前
记录Node.js安全漏洞及其内置Brotli解码器问题
node.js·安全性测试
tommyjiatong3 天前
资安底座连环雷:从 PHP2Shell 到 Node2Shell
node.js·php
SEO_juper3 天前
Bash 交叉验证 robots.txt 和 sitemap:两个文件自相矛盾,页面永远收录不了
开发语言·python·node.js·json·bash
SEO_juper3 天前
Go 站点地图生成器:从首页爬全站,一键生成 sitemap.xml
xml·开发语言·人工智能·golang·node.js·seo·外贸独立站