NodeJS连接MongoDB和mongoose

1.MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。是世界上目前用的最广泛的nosql数据库

2.noSql 翻译过来 not only sql 不仅仅是sql 他就是一个非关系型数据库,它的特点:高性能、易部署、易使用,存储数据非常方便。

注:①关系型数据库,是指采用了关系模型来组织数据的数据库。

   关系模型指的就是二维表格模型,而一个关系型数据库就是由二维表及其之间的联系所组成的一个数据组织。

   关系型数据库的优点:容易理解:二维表结构是非常贴近逻辑世界的一个概念,关系模型相对网状、层次等其他模型来说更容易理解。

             使用方便:通用的SQL语言使得操作关系型数据库非常方便。

             易于维护:丰富的完整性(实体完整性、参照完整性和用户定义的完整性)大大减低了数据冗余和数据不一致的概率

  ②非关系型数据库严格上不是一种数据库,应该是一种数据结构化存储方法的集合。

3.mongodb的优点

  1/面向文档储存的数据库(BSON格式存储)

  2/具有丰富的查询指令

  3/支持索引

  4/具有分片系统

  5/无模式

注:①BSON是由10gen(mongodb)开发的一个数据格式,目前主要用于MongoDB中,是MongoDB的数据存储格式。BSON基于JSON格式,选择JSON进行改造的原因主要是JSON的通用性及JSON的schemaless的特性。

  BSON主要会实现以下三点目标:

  1/更快的遍历速度

  对JSON格式来说,太大的JSON结构会导致数据遍历非常慢。在JSON中,要跳过一个文档进行数据读取,需要对此文档进行扫描才行,需要进行麻烦的数据结构匹配,比如括号的匹配,而BSON对JSON的一大改进就是,它会将JSON的每一个元素的长度存在元素的头部,这样你只需要读取到元素长度就能直接seek到指定的点上进行读取了。

  2/操作更简易对JSON来说

  数据存储是无类型的,比如你要修改基本一个值,从9到10,由于从一个字符变成了两个,所以可能其后面的所有内容都需要往后移一位才可以。而使用BSON,你可以指定这个列为数字列,那么无论数字从9长到10还是100,我们都只是在存储数字的那一位上进行修改,不会导致数据总长变大。当然,在MongoDB中,如果数字从整形增大到长整型,还是会导致数据总长变大的。

  3/增加了额外的数据类型

  JSON是一个很方便的数据交换格式,但是其类型比较有限。BSON在其基础上增加了“byte array”数据类型。这使得二进制的存储不再需要先base64转换后再存成JSON。大大减少了计算开销和数据大小。当然,在有的时候,BSON相对JSON来说也并没有空间上的优势,比如对{“field”:7},在JSON的存储上7只使用了一个字节,而如果用BSON,那就是至少4个字节(32位)

  ②数据分片,将整体数据分摊在多个存储设备上,这样每个存储设备的数据量相对就会小很多,以此满足系统的性能需求

  ③无模式:各种形式的NoSQL数据库有个共同点,那就是它们都没有模式。若要在关系型数据库中存储数据,

  首先必须定义“模式”,也就是用一种预定义结构向数据库说明:要有哪些表格,表中有哪些列,

  每一列都存放何种类型的数据。必须先定义好模式,然后才能存放数据。

4.mongodb的缺点

1/占用空间非常大

2/不支持事务

3/目前已经不维护32位的系统的了

注:事务,一般是指要做的或所做的事情。在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。

5.一个mongodb中可以建立多个数据库。

6.MongoDB的默认数据库为"db",该数据库存储在data目录中。

7.MongoDB的单个实例可以容纳多个独立的数据库,每一个都有自己的集合和权限,不同的数据库也放置在不同的文件中。

8.数据库命名:通过标识符,一般是utf-8字符串,不能为空,不能用local/admin/config这三个

9.mongo的基础指令

show dbs 获取你当前所有的数据库

use dataBase_name 创建数据库(没有-创建/存在-使用)

db 指查询你当前的数据库

db.stats() 查询你当前数据库的状态

db.dropDatabase() 删除你当前的数据库

db.help() 查询帮助

db.version() 获取你当前数据库的版本

db.database_name.help() 查询任意数据库的帮助

db.collection_name.find() 查询你当前集合内的信息

insert插入 db.album.insertOne({‘title’:’xxxx’}),

查看采用db.album.find();

插入多条数据insertMany([{},{},{}])/insert

10.MongoDB-文档

文档是一个键值(key-value)对(即BSON)。MongoDB 的文档不需要设置相同的字段,并且相同的字段不需要相同的数据类型,这与关系型数据库有很大的区别,也是 MongoDB 非常突出的特点。

一个简单的文档例子如下:

{"genres": ["犯罪","剧情" ],"title": "肖申克的救赎"}

11.MongoDB-集合

集合就是 MongoDB 文档组,类似于 RDBMS (关系数据库管理系统:Relational Database Management System)中的表格。

集合存在于数据库中,集合没有固定的结构,这意味着你在对集合可以插入不同格式和类型的数据,但通常情况下我们插入集合的数据都会有一定的关联性。

注:集合的命名不能是空字符串,也不能出现-,0等,不能以system,$开头

12.Collection聚集集合操作

创建一个聚集集合

db.createCollection("collName", {size: 20, capped: true, max: 100});

db.collName.isCapped(); //判断集合是否为定容量

得到指定名称的聚集集合

db.getCollection("account");

得到当前db的所有聚集集合

db.getCollectionNames();

显示当前db所有聚集的状态

db.printCollectionStats();

删除集合

db.collectionname.drop();

添加

db.users.save({name: ‘zhangsan', age: 25, sex: true});

修改

所有数据都添加一个artist

db.albums.updateMany({},{$set:{artist:‘哈哈’}})

db.users.update({age: 25}, {$set: {name: 'changeName'}}, false, true);

相当于:update users set name = ‘changeName' where age = 25;

1/修改的数据不存在---第一个参数false(不添加)true(添加)

2/数据有重复的---第二个参数true符合条件的数据均修改,false默认修改第一条数据

db.users.update({name: 'Lisi'}, {$inc: {age: 50}}, false, true);

相当于:update users set age = age + 50 where name = ‘Lisi';

db.users.update({name: 'Lisi'}, {$inc: {age: 50}, $set: {name: 'hoho'}}, false, true);

相当于:update users set age = age + 50, name = ‘hoho' where name = ‘Lisi';

删除

db.users.remove({age: 132});

查询所有记录

db.userInfo.find();

相当于:select* from userInfo;

查询去重后数据

db.userInfo.distinct("name");

相当于:select distict name from userInfo;

查询age = 22的记录

db.userInfo.find({"age": 22});

相当于: select * from userInfo where age = 22;

查询age > 22的记录

db.userInfo.find({age: {$gt: 22}});

相当于:select * from userInfo where age >22;

查询age < 22的记录

db.userInfo.find({age: {$lt: 22}});

相当于:select * from userInfo where age <22;

查询age >= 25的记录

db.userInfo.find({age: {$gte: 25}});

相当于:select * from userInfo where age >= 25;

查询age <= 25的记录

db.userInfo.find({age: {$lte: 25}});

查询age >= 23 并且 age <= 26

db.userInfo.find({age: {$gte: 23, $lte: 26}});

查询name中包含 mongo的数据

db.userInfo.find({name: /mongo/});

//相当于%%

select * from userInfo where name like ‘%mongo%’;

查询name中以mongo开头的

db.userInfo.find({name: /^mongo/});

select * from userInfo where name like ‘mongo%’;

查询指定列name、age数据

db.userInfo.find({}, {name: 1, age: 1});

相当于:select name, age from userInfo;

查询指定列name、age数据, age > 25

db.userInfo.find({age: {$gt: 25}}, {name: 1, age: 1});

相当于:select name, age from userInfo where age >25;

按照年龄排序

升序:db.userInfo.find().sort({age: 1});

降序:db.userInfo.find().sort({age: -1});

查询name = zhangsan, age = 22的数据

db.userInfo.find({name: 'zhangsan', age: 22});

相当于:select * from userInfo where name = ‘zhangsan' and age = ’22';

查询前5条数据

db.userInfo.find().limit(5);

相当于:select top 5 * from userInfo;

查询10条以后的数据

db.userInfo.find().skip(10);

相当于:select * from userInfo where id not in (

select top 10 * from userInfo

);

限制数据量/几条数据后

db.userInfo.find().limit(10).skip(5);

or与 查询

db.userInfo.find({$or: [{age: 22}, {age: 25}]});

相当于:select * from userInfo where age = 22 or age = 25;

查询第一条数据

db.userInfo.findOne();

相当于:selecttop 1 * from userInfo;

db.userInfo.find().limit(1);

查询某个结果集的记录条数

db.userInfo.find({age: {$gte: 25}}).count();

相当于:select count(*) from userInfo where age >= 20;

查询某一项的记录数目

db.userInfo.find({sex: {$exists: true}}).count();

相当于:select count(sex) from userInfo;

13. 连接MongoDB(两种方法,我们常用第二种方法)

第一步:新建一个文件夹,然后在node中运行npm init,npm i mongodb@2 -D,安装好之后,文件夹下会出来package.json文件,然后会出来node_modules文件夹,注意!!!!在这里一定要在mongodb后面加上版本号@2,这样就会自动安装第二版的最新更新,不然会安装失败。

第二步:在package.json文件下添加"dev": "node index",然后新建一个index.js文件,在index.js中写入代码

方法一:

var mongodb=require('mongodb');//引用mongodb模块
var server=new mongodb.Server('localhost',27017,{auto_reconnect:true});//端口号
var db=new mongodb.Db('zz1906',server,{safe:true});

db.open((err,dbs)=>{
//    dbs==zz1906
    if(err) throw err;
    dbs.collection('info',(err,coll)=>{
//        coll==info
        if(err) throw err;
        
//        console.log(coll.find())
        coll.find().toArray((err,data)=>{
            if(err) throw err;
            console.log(data)
            dbs.close()
        })
    })
})

方法二:

var mongodb=require('mongodb').MongoClient;
var db_str="mongodb://localhost:27017/zz1906";
mongodb.connect(db_str,(err,dbs)=>{
    //dbs==zz1906
    if(err) throw err;
    dbs.collection('info',(err,coll)=>{
        //coll==info
        
        // if(err) throw err;//打印出来会有很多代码冗余
        // console.log(coll.find())
        // dbs.close()
        
        
        if(err) throw err;
        coll.find().toArray((err,data)=>{//查(减少了很多冗余代码)
            if(err) throw err;
            console.log(data);
            dbs.close()
        })
        coll.insert({title:'战狼'},()=>{//增
            console.log('success');
            dbs.close();
        })
        coll.remove({title:'吴京'},()=>{//删
            console.log('success');
            dbs.close();
            
        })
        coll.update({name:"zhangsan"},{$set:{name:'张三'}},()=>{//改
            console.log('success');
            dbs.close();
            
        })
        
        
    })
})

14. 连接mongooes

安装mongooes,在node中输入npm i mongoose --save-dev, index.js中输入代码

var mongoose=require('mongoose');
var db_str="mongodb://localhost:27017/zz1906";
mongoose.connect(db_str)
mongoose.connection.on('connected',()=>{
    console.log('连接成功')
})
mongoose.connection.on('error',()=>{
    console.log('error')
})
mongoose.connection.on('disconnected',()=>{
    console.log('断开连接')
})

var schema=new mongoose.Schema({
    name:{type:String,require:true},
    content:{type:String,require:true}
})

var Cat=new mongoose.model('info',schema)
// Cat.find({},(err,data)=>{//查询
//     if(err) throw err;
//     console.log(data)
//     mongoose.disconnect()
// })
// Cat.create({name:'小明',content:'helloworld'},()=>{//增
//     console.log('success')
//     mongoose.disconnect()
// })
// Cat.update({name:'小明'},{$set:{content:'hi'}},()=>{//改
//     console.log('success')
//     mongoose.disconnect()
// })
// Cat.remove({name:'小明'},()=>{//删
//     console.log('success');
//     mongoose.disconnect()
// })

15. 也可以运用软件robo3t来对数据库进行操作