数据库:mongodb 数据库增删改查

/* https://www.cnblogs.com/zxiong/p/6149715.html (不可用,修改系统崩溃了)—mongoDB服务器开机自启动: */
安装mongoDB: https://blog.csdn.net/yzh_1346983557/article/details/81735755
mongoDB远程连接: https://www.cnblogs.com/chenhaoyu/p/9965067.html
linux开放端口:https://www.cnblogs.com/sxmny/p/11224842.html
MongoDB可视化使用 https://blog.csdn.net/jamin_liu_90/article/details/88017013
(个人不建议在compass中建立文档,因为工具主体功能是提供数据的可视化,方面观察,不是在插入、更新等方面)
windows安装方式: https://www.runoob.com/mongodb/mongodb-window-install.html

linux下
1)启动mongodb服务 /usr/local/mongodb/bin下: ./mongodb/mongod
// ./mongod -f mongodb.conf //按照配置启动mongodb服务
2)打开mongodb命令行: mongo

如果报错 100说明服务已经启动,无需再次启动
about to fork child process, waiting until server is ready for connections.
forked process: 8793
ERROR: child process failed, exited with error number 100

开始。。。

windows开启mongodb数据库: net start MongoDB

show dbs // 所有数据库
use 数据库名 // 创建或打开数据库,如use test
show collections // 查看当前数据库下的集合(即表)
db.createCollection("集合名称") // 
db.createCollection("集合名称",{"限制条件":"值"}) //限制集合大小, 如db.createCollection("集合名称",{capped:true,size:10});
db.集合名称.drop() // 删除集合
db.集合名.find() //查询集合下的数据,不传条件查询全部如db.user.find()
db.集合名.findOne({"查询条件":"值"})//db.user.findOne({"name":"zhangsan"})

nodejs平台修改插件

var url = "mongodb://localhost:27017/";
var dbName = 'test'
var collectionName = 'user'
// 基于class+promise封装数据库请求库
var MongoClient = require('mongodb').MongoClient;
class DAO {
    constructor(url, dbName, collectionName) {
        this.url = url
        this.dbName = dbName
        this.collectionName = collectionName
    }
    _connect (Methods) {
        if (Methods === 'query') {
            return new Promise(function (resolve, reject) {
                MongoClient.connect(url, {
                    useNewUrlParser: true
                }, function (err, client) {
                    if (err) return reject(err)
                    console.log("Connected successfully to server");
                    resolve(client)
                });
            })
        } else {
            return new Promise(function (resolve, reject) {
                MongoClient.connect(url, {
                    useNewUrlParser: true
                    , useUnifiedTopology: true // query不能有这个对象
                }, function (err, client) {
                    if (err) return reject(err)
                    console.log("Connected successfully to server");
                    resolve(client)
                });
            })
        }

    }
    insert (obj, isMany) {
        //obj为数组对象
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(dbName)
                if (isMany) {
                    //插入多条
                    db.collection(this.collectionName).insertMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
                else {
                    db.collection(this.collectionName).insertOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
            })
        })
    }
    del (obj, isMany) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let db = client.db(this.dbName)
                if (isMany) {
                    //插入多条
                    db.collection(this.collectionName).deleteMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
                else {
                    db.collection(this.collectionName).deleteOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
            })
        })
    }
    update (filter, updater) {
        return new Promise((resolve, reject) => {
            this._connect().then(client => {
                let updateCpy = { $set: updater }
                let db = client.db(dbName)
                if (true) {
                    //更新多条
                    db.collection(this.collectionName).updateMany(filter, updateCpy).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
                else {
                    db.collection(this.collectionName).updateOne(filter).then(res => {
                        console.log(res)
                        // resolve(res)
                        resolve('123')
                        client.close()
                    })
                }
            })
        })
    }
    query (obj) {
        obj = obj || {} //查询条件,不传就默认全部
        return new Promise((resolve, reject) => {
            this._connect('query').then(client => {
                // console.log(this.dbName, this.collectionName, obj)
                let db = client.db(dbName)
                let queryRes = db.collection(this.collectionName).find(obj)
                console.log(queryRes)
                queryRes.toArray((err, data) => {
                    resolve(data)
                })
                client.close()
            })
        })
    }
}

// 启动mongodb服务: net start mongodb
// mongodb日志文件:MONGODB安装包下的配置文件mongod.cfg记录着日志文件的位置

const dao = new DAO('mongodb://localhost:27017/', 'test', 'user')
// 一:插入数据---ok
// 1) 多条
// let arr = []
// for (let i = 1; i < 11; i++) {
//     arr.push({ name: '路人' + i, age: i })
// }
// dao.insert(arr, true).then(res => {
//     console.log(res)
// })
// console.log('--------')
// 2) 1条
// dao.insert({ name: 'admin', age: '123456' }).then(res => {
//     // console.log(res)
//     console.log(res.result)
// })
// 3)没有该数据再去添加
// dao.query({ name: 'admin' }).then(res => {
//     if (res.length > 0) {
//         console.log('数据已经存在')
//     } else {
//         dao.insert({ name: 'admin', age: '12345678' }).then(res => {
//             console.log(res.result)
//         })
//     }
// })
//二:删除数据(类型值必须一致)---ok
// 1)多条
// dao.del({ name: 'xushilin', age: '20' }, true).then(res => {
//     // console.log(res)
//     console.log(res.result)
//     if (res.result && res.result.n > 0) {
//         console.log('删除成功', '删除数量:' + res.result.n)
//     }
//     else if (res.result && res.result.n == 0) {
//         console.log('该数据不存在')
//     } else {
//         console.log('暂无法删除')
//     }
// })
// 2)1条(有多条匹配也只会删一条)
// dao.del({ name: 'xuxian', age: 20 }).then(res => {
//     // console.log(res)
//     console.log(res.result)
//     // 删除成功后 { n: 1, ok: 1 } n代表删除的数量
// if (res.result && res.result.n > 0) {
//     console.log('删除成功','删除数量:'+res.result.n)
//  }
// else if (res.result && res.result.n == 0) {
//     console.log('该数据不存在')
//  } else { 
//      console.log('暂无法删除')
//  }
// })

// 三:改---ok 
let filter = { name: '路人9', age: 20 }
let obj = { name: '路人9', age: 20 }
dao.update(filter, obj).then(res => {
    console.log(res)
    console.log(res.result)
    // 如果要改的数据不存在:{ n: 0, nModified: 0, ok: 1 }
    if (res.result && res.result.nModified > 0 && res.result.n > 0) {
        console.log('修改成功')
    } else if (res.result && res.result.nModified == 0) { 
        console.log('修改失败或修改的值一致')
    }else{
        console.log('暂无法修改')
    }
})

// 四:查询----ok
// 1)查询所有数据
// dao.query().then(res => {
//     console.log(res)
// })
// 2)根据条件查询数据
// dao.query({ name: 'admi1n' }).then(res => {
//     // 没有查到就是空数据[]
//     if (res && res.length > 0) {
//         console.log(res)
//     } else {
//         console.log(res)
//         console.log('暂未查询到数据')
//     }
// })

// const ObjectId = require('mongodb').ObjectId;
// console.log(ObjectId)

module.exports = DAO
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值