当前位置: 首页 > news >正文

Node.js——操作MongoDB

操作MongoDB

    • 1、MongoDB概述
    • 2、安装MongoDB数据库
    • 3、安装MongoDB包
    • 4、连接MongoDB
    • 3、插入数据
    • 5、更新数据
    • 6、查询数据
    • 7、删除数据
    • 8、索引操作
    • 9、事务(MongoDb 4.0+)
    • 10、与 Express 结合示例

1、MongoDB概述

由于MongoDB数据库在JavaScript脚本环境中支持BSON对象(JSON对象的二进制形式)的存取,因此对于数据的存取的效率是非常高的。在MongoDB数据库中,将每一条等待插入的数据记录存储在内存中,因此,该数据库是一种非阻塞型数据库,在需要记载大量日志数据、实时测量数据或实时统计数据时,该数据库可以达到令人满意的效果。由于MongoDB数据库支持在查询语句内部使用JavaScript函数,也大大加强了它读取数据的能力。

MongoDB数据库中支持的数据类型:

数据类型说明数据使用示例
Array数组cardsInHand:[9,4,3]
Boolean布尔类型,只允许true或false值hasBeenRead:false
Code数据库内部可运行的一段JavaScript脚本代码new BSON.Code(
‘function quotient(dividend, divisor){
return divisor == 0 ? 0:dividen / divisor;}’);
Date当前日期和时间lastUpdated:new Date()
DBRef数据库引用bestFriendId:
new BSON.DBRef(‘users’, friendObjectId)
Integer整数值pageViews:50
Long长整数值starsInUniverse=new BSON.Long(“100000000000000000”);
Hash一个“键值/键名”形式的数据字典userName:{‘first’:‘Sam’, ‘last’:‘Smith’}
Nullnull值bestFriend: null
ObjectIDMongoDB数据库中用于索引对象的一个12字节的代码,其表现形式为一个24位的十六进制字符串
String字符串fullName: ‘Sam Smith’

2、安装MongoDB数据库

可以在MongoDB官网(网址为http://www.mongodb.org/)上根据操作系统类型下载相应的MongoDB数据库安装包。在下载及解压缩后的安装包的bin文件夹中,包含了一系列可执行文件。其中用于运行数据库服务器的可执行文件名为mongod,用于运行与数据库服务器相连接的客户端的可执行文件名为mongo。

在运行数据库服务器之前,需要挑选磁盘中一个空的文件夹,在数据库服务器运行时将会在其中写入一些运行数据库服务器时所需使用的文件。

mongod-dbpath<用户挑选的磁盘文件夹名>

3、安装MongoDB包

当用户需要在Node.js应用程序中执行MongoDB数据库连接时,可以下载MongoDB包,在下载的包中包含了MongoDB本地驱动程序。可以使用如下所示的命令安装MongoDB包。

npminstallmongodb

在安装了MongoDB包后,可以使用如下所示的表达式来使用MongoDB模块。

const{MongoClient}=require("mongodb");

Node.js >= 16
MongoDB >= 4.x

4、连接MongoDB

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();console.log("连接成功");constdb=client.db("testdb");constcollection=db.collection("users");// 这里写你的操作}finally{awaitclient.close();}}main().catch(console.error);
连接成功

3、插入数据

插入单条:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//插入单条数据constresult=awaitcollection.insertOne({name:"张三",age:25,email:"123@123.com"});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
{acknowledged:true,insertedId:newObjectId('69d1e8f5add3ecc5377bc361')}

插入多条:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//插入多条数据constresult=awaitcollection.insertMany([{name:"李四",age:30},{name:"王五",age:28}]);console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
{acknowledged:true,insertedCount:2,insertedIds:{'0':newObjectId('69d1e93ef05ee234c2511e27'),'1':newObjectId('69d1e93ef05ee234c2511e28')}}

5、更新数据

更新单条:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//更新单条数据constresult=awaitcollection.updateOne({name:"张三"},{$set:{age:260}});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
{acknowledged:true,modifiedCount:1,upsertedId:null,upsertedCount:0,matchedCount:1}

更新多条:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//更新多条数据constresult=awaitcollection.updateMany({age:{$lt:30}},{$inc:{age:1}});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
{acknowledged:true,modifiedCount:2,upsertedId:null,upsertedCount:0,matchedCount:2}

6、查询数据

查询所有:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//查询所有数据constresult=awaitcollection.find().toArray();console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
[{_id:newObjectId('69d1e8e60a6eabb1203b66d5'),name:'张三',age:260,email:'123@123.com'},{_id:newObjectId('69d1e8f5add3ecc5377bc361'),name:'张三',age:26,email:'123@123.com'},{_id:newObjectId('69d1e93ef05ee234c2511e27'),name:'李四',age:30},{_id:newObjectId('69d1e93ef05ee234c2511e28'),name:'王五',age:29}]

条件查询

constresult=awaitcollection.find({name:"张三"}).toArray();console.log(result);
[{_id:newObjectId('69d1e8e60a6eabb1203b66d5'),name:'张三',age:260,email:'123@123.com'},{_id:newObjectId('69d1e8f5add3ecc5377bc361'),name:'张三',age:26,email:'123@123.com'}]

高级查询:

constresult=awaitcollection.find({age:{$gt:25}}).toArray();console.log(result);
[{_id:newObjectId('69d1e8e60a6eabb1203b66d5'),name:'张三',age:260,email:'123@123.com'},{_id:newObjectId('69d1e8f5add3ecc5377bc361'),name:'张三',age:26,email:'123@123.com'},{_id:newObjectId('69d1e93ef05ee234c2511e27'),name:'李四',age:30},{_id:newObjectId('69d1e93ef05ee234c2511e28'),name:'王五',age:29}]

7、删除数据

删除单条:

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");//删除单条数据constresult=awaitcollection.deleteOne({name:"李四"});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);
{acknowledged:true,deletedCount:1}

删除多条:

constresult=awaitcollection.deleteMany({age:{$gt:50}});console.log(result);
{acknowledged:true,deletedCount:1}

8、索引操作

创建索引:

constresult=awaitcollection.createIndex({email:1},{unique:true});console.log(result);
email_1

查看索引:

constindexes=awaitcollection.indexes();console.log(indexes);
[{v:2,key:{_id:1},name:'_id_'},{v:2,key:{email:1},name:'email_1',unique:true}]

9、事务(MongoDb 4.0+)

const{MongoClient}=require("mongodb");consturi="mongodb://localhost:27017";// 本地// Atlas: mongodb+srv://user:pwd@cluster0.xxx.mongodb.net/asyncfunctionmain(){constclient=newMongoClient(uri);try{awaitclient.connect();constdb=client.db("testdb");constcollection=db.collection("users");constsession=client.startSession();try{session.startTransaction();awaitcollection.insertOne({name:"事务测试"},{session});awaitsession.commitTransaction();}catch(e){awaitsession.abortTransaction();}finally{session.endSession();}}finally{awaitclient.close();}}main().catch(console.error);

10、与 Express 结合示例

app.get("/users",async(req,res)=>{constusers=awaitcollection.find().toArray();res.json(users);});
http://www.jsqmd.com/news/592117/

相关文章:

  • JSON Formatter终极实战:如何高效构建交互式JSON可视化组件?
  • 利用介质超表面实现宽带任意阶贝塞尔光束的生成:以2017年Light ScienceAppl...
  • 半刚性连接的一些概念
  • 智鼎MAP性格测试避坑指南:如何避免‘人设崩塌’拿到高分?
  • OneNote Markdown导出工具终极指南:3步完成笔记迁移
  • 告别手动抢茅台!Campus-imaotai自动预约系统完整指南
  • 3分钟快速指南:如何用免费工具找回加密压缩包密码
  • YOLO26涨点改进| TPAMI 2025顶刊 |独家创新首发、Conv改进篇| 引入LPRM局部像素关系卷积模块,提升细节表达和边界定位能力,助力小目标检测、语义分割、图像分割、图像增强有效涨点
  • 5个效率倍增方法:Kazumi播放器无缝访问与快速启动指南
  • 坐标转换技术解析:多坐标系无缝切换方案
  • 投稿实战复盘篇(1)——电力电子顶刊TIE/TPEL审稿心路与策略
  • Kazumi快捷访问全攻略:从场景需求到跨平台实现
  • WeChatMsg完全攻略:Mac微信聊天记录管理与分析的终极解决方案
  • 抖音无水印视频批量采集工具:技术架构与实战应用指南
  • 利用快马平台ai辅助,十分钟搭建lstm股票价格预测模型原型
  • 如何5分钟为Unity游戏添加免费实时翻译:XUnity.AutoTranslator终极指南
  • SEO部门如何制定长期的优化策略_SEO 部门如何有效地管理网站的技术优化
  • 在Android上实现高效文本管理的终极指南:Markor完全解析
  • 2026届最火的AI辅助论文助手实测分析
  • LSPatch终极指南:5分钟掌握免Root安卓应用修改技术
  • 手机域名专门给手机用吗,北京华瑞网研的服务好用吗 - 工业设备
  • 夸克网盘自动化助手:告别手动操作,享受智能云存储管理
  • 新手福音:通过快马平台生成centos安装openclaw的零基础图文指南
  • 如何快速掌握QtScrcpy:终极Android投屏与PC操控完全指南
  • IDM激活脚本完整教程:永久免费使用Internet Download Manager的终极方案
  • GEMMA-3像素站保姆级教程:一键部署,体验90年代复古AI界面
  • 高效获取抖音无水印封面:自媒体素材批量处理指南
  • 番茄小说下载神器:一键生成EPUB电子书的高效解决方案
  • 实战应用:在快马平台上构建生产级openclaw升级命令管理系统
  • PCB表面工艺抉择:沉金与喷锡在实战中的性能博弈