node操作数据库

本文详细介绍使用MongoDB进行数据库连接、查询、插入、更新等基本操作,包括如何使用管道查询进行复杂的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我这个是官方自己的连接方式,npm上有一个mongose连接,这个有时间我再写

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

const url = 'mongodb://localhost:27017';

const dbName = 'test';

const client = new MongoClient(url, { useUnifiedTopology: true });

client.connect((err) => {
    if (err) {
        console.log(err);
        return;
    }
    console.log('连接数据库成功');
    let db = client.db(dbName).collection('user');
    // 查找
     db.find({ 'username': '张三' }).toArray((err, data) => 						   {
             console.log('data', data)
             client.close();
        })
     console.log(db.collection('user').count())  // 一共又多少个
     // 插入
     db.insert({ 'username': 'zhangsan', 'password': 'admin' }, (err, result) => {
         if (err) {
             console.log(err)
         } else {
             console.log(result)
         }
     })
     // 更新,要用$set,否则会将全部字段替换,没写的会消失
     db.update({ 'username': 'user1' }, { $set: { 'username': 'zly' } }, (err, result) => {
         if (err) {
             console.log(err)
         } else {
             console.log('xiugia')
             console.log(result)
         }
     })
     // 管道查询
    db.aggregate([
             {
             	$project: { username: 1, password: 1 } // 匹配那些字段
             }, 
             {
        	     $match: { password: 'password2' } // 匹配条件
             }, 
             {
        	     $group: { _id: 'username', total: { $sum: '$num' } } // _id固定写法,total表示分组之后的计算,$sun表示和
        	 },
        	 {
        	     $skip: 1 // 跳过1条
        	 },
        	 {
        	     $limit: 2 // 返回两条
        	 },
        	 {
            	$lookup: {
                	from: 'other', // 关联查询的表
                	localField: '_id', // 主表的关联字段
                	foreignField: 'order_id', // 附表的查询
                	as: 'items' // 把查询结果放到主表查询出来结果的那个字段里面
             }
       	 }
   	 ]).toArray(function(err, data) {
        if (err) {
            console.log(err)
        }
        console.log('data', data)
    })
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值