Node.js——操作MongoDB

张开发
2026/4/5 14:27:43 15 分钟阅读

分享文章

Node.js——操作MongoDB
操作MongoDB1、MongoDB概述2、安装MongoDB数据库3、安装MongoDB包4、连接MongoDB3、插入数据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:falseCode数据库内部可运行的一段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:50Long长整数值starsInUniversenew BSON.Long(“100000000000000000”);Hash一个“键值/键名”形式的数据字典userName:{‘first’:‘Sam’, ‘last’:‘Smith’}Nullnull值bestFriend: nullObjectIDMongoDB数据库中用于索引对象的一个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 16MongoDB 4.x4、连接MongoDBconst{MongoClient}require(mongodb);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();console.log(连接成功);constdbclient.db(testdb);constcollectiondb.collection(users);// 这里写你的操作}finally{awaitclient.close();}}main().catch(console.error);连接成功3、插入数据插入单条const{MongoClient}require(mongodb);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//插入单条数据constresultawaitcollection.insertOne({name:张三,age:25,email:123123.com});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);{acknowledged:true,insertedId:newObjectId(69d1e8f5add3ecc5377bc361)}插入多条const{MongoClient}require(mongodb);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//插入多条数据constresultawaitcollection.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);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//更新单条数据constresultawaitcollection.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);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//更新多条数据constresultawaitcollection.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);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//查询所有数据constresultawaitcollection.find().toArray();console.log(result);}finally{awaitclient.close();}}main().catch(console.error);[{_id:newObjectId(69d1e8e60a6eabb1203b66d5),name:张三,age:260,email:123123.com},{_id:newObjectId(69d1e8f5add3ecc5377bc361),name:张三,age:26,email:123123.com},{_id:newObjectId(69d1e93ef05ee234c2511e27),name:李四,age:30},{_id:newObjectId(69d1e93ef05ee234c2511e28),name:王五,age:29}]条件查询constresultawaitcollection.find({name:张三}).toArray();console.log(result);[{_id:newObjectId(69d1e8e60a6eabb1203b66d5),name:张三,age:260,email:123123.com},{_id:newObjectId(69d1e8f5add3ecc5377bc361),name:张三,age:26,email:123123.com}]高级查询constresultawaitcollection.find({age:{$gt:25}}).toArray();console.log(result);[{_id:newObjectId(69d1e8e60a6eabb1203b66d5),name:张三,age:260,email:123123.com},{_id:newObjectId(69d1e8f5add3ecc5377bc361),name:张三,age:26,email:123123.com},{_id:newObjectId(69d1e93ef05ee234c2511e27),name:李四,age:30},{_id:newObjectId(69d1e93ef05ee234c2511e28),name:王五,age:29}]7、删除数据删除单条const{MongoClient}require(mongodb);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);//删除单条数据constresultawaitcollection.deleteOne({name:李四});console.log(result);}finally{awaitclient.close();}}main().catch(console.error);{acknowledged:true,deletedCount:1}删除多条constresultawaitcollection.deleteMany({age:{$gt:50}});console.log(result);{acknowledged:true,deletedCount:1}8、索引操作创建索引constresultawaitcollection.createIndex({email:1},{unique:true});console.log(result);email_1查看索引constindexesawaitcollection.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);consturimongodb://localhost:27017;// 本地// Atlas: mongodbsrv://user:pwdcluster0.xxx.mongodb.net/asyncfunctionmain(){constclientnewMongoClient(uri);try{awaitclient.connect();constdbclient.db(testdb);constcollectiondb.collection(users);constsessionclient.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){constusersawaitcollection.find().toArray();res.json(users);});

更多文章