Node.js-MongoDB数据库:连接、增删改查操作

本篇介绍使用原生驱动连接和操作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();//关闭连接
});

 运行结果如下:

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Data菌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值