MongoDb数据库基础

先安装插件node-snippets

  1. http模块
//表示引入http模块
var http = require('http');
/*
    req   获取客服端传过来的信息
    res   给浏览器响应信息
*/
http.createServer((req, res) => { //创建一个服务器
    console.log(req.url); //获取url
    //设置响应头
    //状态码为200,文件类型为html,字符集是utl-8
    res.writeHead(200, { "Content-Type": "text/html;charset='utf-8" });
    res.write("<head><meta charset='UTF-8'></head>");//解决中文乱码
    res.write("this is nodejs");
    res.end(); //结束响应 ---一定要调用
}).listen(3000); //端口号
console.log('Server running at http://127.0.0.1:8081/');

2.Nodejs自启动工具 supervisor
只要修改代码,就会改变运行
安装:

npm install -g supervisor

利用HTTP模块Url模块Path模块,Fs模块创建一个静态WEB服务器

const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
    //http://127.0.0.1:8081/index.html
    //1.获取地址
    console.log(req.url);
    let pathname = req.url;
    pathname = pathname == "/" ? '/index.html' : pathname
        //2.通过fs模块读取文件
    if (pathname != "/favicon.ico") {
        fs.readFile("./static" + pathname, (err, data) => {
            if (err) {
                res.writeHead(404, { 'Content-Type': "text/html;charset='utf-8'" });
                res.end("页面不存在");
            }
            res.writeHead(200, { 'Content-Type': "text/html;charset='utf-8'" });
            res.end(data);
        })
    }


}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

但是这个静态资源服务器只能加载html的文件,不能加载css跟js的文件,导致页面渲染不了

const http = require('http');
const fs = require('fs');
const common = require('./module/common.js');
const path = require('path');
//因为json文件会报错,所以用url模块来消除json文件的后缀
const url = require('url');
http.createServer(function(req, res) {
    //http://127.0.0.1:8081/index.html
    //1.获取地址
    console.log(req.url);
    let pathname = url.parse(req, res).pathname;
    pathname = pathname == "/" ? '/index.html' : pathname

    let extname = path.extname(pathname); //获取后缀名
    //2.通过fs模块读取文件
    if (pathname != "/favicon.ico") {
        fs.readFile("./static" + pathname, (err, data) => {
            if (err) {
                res.writeHead(404, { 'Content-Type': "text/html;charset='utf-8'" });
                res.end("页面不存在");
            }
            var mime = common.getMime(extname)
            res.writeHead(200, { 'Content-Type': "" + mime + ";charset='utf-8'" });
            res.end(data);
        })
    }


}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

MongoDb

下载MongoDb
MongoDb
下载完后再要path下配置环境MongoDb的bin目录
在这里插入图片描述
打开cmd输入:mongo命令看看是否成功(同时也是连接命令)

  • MongoDb数据库创建,删除,表(集合)创建删除,数据的增删改查

看电脑上有哪些数据库-cnd命令(show dbs)

清屏:cls

在这里插入图片描述
如果真的想把这个数据库创建成功,那么必须插入一个数据。 数据库中不能直接插入数据,只能往集合(collections)中插入数据。下面命令表示给 itying 数 据库的 user 表中插入数据。

查找数据:
在这里插入图片描述
在这里插入图片描述
修改数据:
修改里面还有查询条件。你要该谁,要告诉 mongo。 查找名字叫做小明的,把年龄更改为 16 岁:

db.student.update({“name”:“小明”},{$set:{“age”:16}});

查找数学成绩是 70,把年龄更改为 33 岁:

db.student.update({“score.shuxue”:70},{$set:{“age”:33}});

更改所有匹配项目:"

db.student.update({“sex”:“男”},{$set:{“age”:33}},{multi: true});

完整替换,不出现$set 关键字了: 注意

db.student.update({“name”:“小明”},{“name”:“大明”,“age”:16});

删除数据

db.collectionsNames.remove( { “borough”: “Manhattan” } )
db.users.remove({age: 132});

  • MongoDb大数据查询优化、MongoDb索引、复合索引、唯一索引、explain分析查询速度

设置索引可以让我们的查询速度更快(当数据库的量大的时候可以提现出来)
在这里插入图片描述
对于上面创建索引,MongoDb都会根据keyname和索引的方向为新创建的索引自动分配一个索引名,下面的命令可以在创建索引时为其指定索引名,如:

db.表名.ensureIndex({“username”:1},{“name”:“userindex”}})

随着集合的增长,需要针对查询中大量的排序做索引。如果没有对索引的键调用sort,MongoDB需要将所有数据提取到内存并排序。因此在做无索引排序时,如果数据量过大以至无法在内存中进行排序,此时MongoDB将会报错

索引的一些参数
在这里插入图片描述

  • Mongodb4.x 的使用以及 Mongodb 账户权 限配置

保证数据的安全性

  1. Mongodb 账户权限配置
//先进入admin数据库
use admin 
//创建管理员
db.createUser({
	 user:'admin', 
	 pwd:'123456', 
	 roles:[{role:'root',db:'admin'}] 
 })
  1. 第二步修改 Mongodb 数据库配置文件
路径:C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg 
配置: security: 				
			authorization: enabled
  1. 第三步重启 mongodb 服务cmd命令services.msc。在里面找到MongoDB server并重新启动

  2. 第四步用超级管理员账户连接数据库

本地连接:mongo admin -u 用户名 -p 密码
远程连接:mongo 192.168.1.200:27017/test -u user -p password

  1. 第五步给 eggcms 数据库创建一个用户 只能访问 eggcms 不能访问其他数据库
//先进入eggcms 数据库
use eggcms 
//创建管理员
db.createUser({ 
	user: "eggadmin", 
	pwd: "123456", 
	roles: [{role:"dbOwner",db:"eggcms"}] 
})

Mongodb 账户权限配置中常用的命令
在这里插入图片描述

Mongodb 数据库角色
在这里插入图片描述

参考:Mongodb 数据库角色

连接数据库的时候需要配置账户密码

const url = 'mongodb://admin:123456@localhost:27017/';
  • MongoDB多表查询及高级查询aggregate聚合管道

MongoDB Aggregation 管道操作符与表达式

管道操作 符Description
$project增加、删除、重命名字段
$match条件匹配。只满足条件的文档才能进入下 一阶段
$limit限制结果的数量
$skip跳过文档的数量
$sort条件排序
$group条件组合结果 统计
$lookup$lookup 操作符 用以引入其它集合的数 据 (表关联查询)

管道表达式:
在这里插入图片描述

代码示例:


db.order.aggregate([
{	
	//要求查找 order 只返回文档中 trade_no 和 all_price 字段
	$project:{ trade_no:1, all_price:1 }  
},
{
	//用于过滤文档。用法类似于 find() 方法中的参数。
	$match:{"all_price":{$gte:90}}
},
{ 
	//将集合中的文档进行分组,可用于统计结果。
	$group: {_id: "$order_id", total: {$sum: "$num"}} 
},
{
	//将集合中的文档进行排序。
	$sort:{"all_price":-1}
},
{ 
	//限制结果的数量
	$limit:1 
},
{
	//跳过文档的数量
	$skip:1
},
 {
 	//$lookup 操作符 用以引入其它集合的数 据 (表关联查询)
 	//order表关联order_item表,关联关系order_id,存放位置items
      $lookup:
        {
          from: "order_item",
          localField: "order_id",
          foreignField: "order_id",
          as: "items"
        }
   }

])

MongoDB数据库的备份以及还原
1.mongodb数据备份导出语法:

mongodump -h dbhost -d dbname -o dbdirectory
参数说明:
-h:Mongodb所在服务器,例如127.0.0.1
-d:需要备份的数据实例,例如test
-o:备份的数据存放位置,例如:/home/mongodump

实例如下:

mongodump -h 127.0.0.1 -d itying -o D:\web\sjk

2.mongodb数据恢复导入语法:

mongorestore -h dbhost -d dbname dbdirectory
参数说明:
h:Mongodb所在服务器
-d:需要备份的数据实例
–drop:恢复的时候,先删除当前数据,然后恢复备份的数据

导入实例:

mongorestore -h 127.0.0.1 -d itying D:\web\sjk\itying

3.数据库有用户密码认证的参考下面命令

 mongodump -h localhost:127.0.0.1 -d itying -u test -p testpwd -o D:\web\sjk
mongodump -h localhost:127.0.0.1 -d itying -c order --dir D:\web\sjk\itying\user.bsom -u test -p testpwd
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值