本篇介绍使用原生驱动连接和操作MongoDB数据库。
先安装mongodb驱动模块。
代码如下:【注意:先确认MongoDB数据库是启动的】【注意】注释部分代码测试特定的API功能。
/**
* MongoDB数据库操作
*/
const mongodb = require("mongodb");
const conn = mongodb.MongoClient.connect("mongodb://localhost:27017",{useNewUrlParser:true},function(err,client){
if(err) throw err;
console.log("成功连接MongoDB数据库");
let db = client.db("studentdb");//选择连接的数据库
let col = db.collection("students");//选择集合
//--------添加记录-----------
//向集合中添加单个文档数据
let studentInfo = {"Id":1001,"Name":"W","Age":24,"Weight":45.5};
col.insertOne(studentInfo,(err,res)=>{
if(err) throw err;
console.log("单个文档添加成功");
});
//向集合中添加多个文档数据
let studentInfoArr = [{"Id":1002,"Name":"Jhon","Age":35,"Weight":35.2},{"Id":1003,"Name":"Julia","Age":28,"Weight":55.2}];
col.insertMany(studentInfoArr,(err,res)=>{
if(err) throw err;
console.log("多个文档添加成功");
});
//----------查询记录----------
col.find({}).toArray((err,res)=>{
if(err) throw err;
console.log("====查询所有记录如下=======");
console.log(res);
});
//根据查询条件查询
col.find({"Id":1001}).toArray((err,res)=>{
if(err) throw err;
console.log("====根据查询条件查询特定记录如下=======");
console.log(res);
});
//根据查询条件和过滤选项查询
col.find({"Age":{"$gt":25}},{projection:{},sort:{"Weight":-1}}).toArray((err,res)=>{
if(err) throw err;
console.log("====根据查询条件和选项设置查询记录如下=======");
console.log(res);
});
//------修改记录--------
col.updateMany({"Id":1001},{$set:{"Weight":65.5}},(err,res)=>{
if(err) throw err;
console.log("发生修改的文档数:"+res.modifiedCount);
});
//-----删除记录-------
col.deleteMany({"Id":1003},(err,res)=>{
if(err) throw err;
console.log("删除符合条件的记录数:",res.deletedCount);
});
client.close();//关闭连接
});
运行结果如下: