MongoDB数据库使用详解

Mongoose第三方包

使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose

使用npm install mongoose命令下载

数据库相关概念

术语解释说明
database数据库,mongoDB数据库软件中可以建立多个数据库
collection集合,一组数据的集合,可以理解为JavaScript中的数组,类似于表
document文档,一条具体的数据,可以理解为JavaScript中的对象 ,类似于表内的一条记录
field字段,文档中的属性名称,可以理解为JavaScript中的对象属性

连接数据库

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/demonstration',{ useNewUrlParser: true })
        .then(()=>console.log('连接成功'))
        .catch(()=>console.log('连接失败'));

创建集合

创建一个学生集合,属性为[学号,名字,年龄,是否毕业]

 //创建规则
var studentSchema=new mongoose.Schema({
	sno:String,
	sname:String,
	sage:Number,
    hobbies:[String],
	isGraduation:Boolean
});
 //创建集合并运用规则
 //在mongoDB数据库内Student集合会自动变为students
var Student=mongoose.model('Student',studentSchema); 

插入文档

创建文档
  • 通过save()方法

    //实例集合并使用.save()方法
    var student =new Student({
    	sno:'2018001',
    	sname:'小明',
    	sage:20,
        hobbies:['读书','跑步'],
    	isGraduation:false
    });
    student.save();
    
  • 通过create()方法

    返回的是一个promise对象

    Student.create({
    	sno:'2018001',
    	sname:'小明',
    	sage:20,
        hobbies:['读书','跑步'],
    	isGraduation:false
    }).then(()=>console.log('插入成功'))
    .catch(()=>console.log('插入失败'));
    
mongoDB数据库导入数据

找到mongodb数据库工具的安装目录(即找bin目录下的mongoimport.exe文件是否存在,未找到的可取官网下载)

将安装目录下的bin目录放置在系统环境变量Path中。

命令行命令:

mongoimport –d 数据库名称 –c 集合名称 –-file 要导入的数据文件

mongoimport -d demonstration -c students --file ./student.json

MongoDB增删改查操作

查询文档

find()返回值是一个集合

findOne()返回值是一个对象

  • 查询集合中所有文档

    //两个语句都可以
    Student.find().then(result=>console.log(result));
    Student.find({}).then(result=>console.log(result));
    
  • 根据条件查找文档

    查询年纪为18的文档

    Student.find({sage:18}).then(result=>console.log(result));
    
  • 查出结果为多个文档中的第一个

    Student.findOne({sage:18}).then(result=>console.log(result));
    
  • 匹配大于 小于

    查询年纪大于18,小于20的文档

    Student.find({sage:{$gt:18,$lt:20}}).then(result=>console.log(result));
    
  • 匹配包含

    查询爱好内有跑步的记录

    Student.find({hobbies:{$in:['跑步']}}).then(result=>console.log(result));
    
  • 选择要查询的字段

    只显示sno sage 不显示_id 在前面加 -

    Student.find().select('sno sage -_id').then(result => console.log(result))
    
  • 将数据按照年龄进行排序 默认升序 想要降序在前面加-

    Student.find().sort('sage').then(result => console.log(result))
    
  • skip 跳过多少条数据 limit 限制查询数量

    Student.find().skip(1).limit(1).then(result => console.log(result))
    
删除文档
  • 删除单个

    Student.findOneAndDelete({}).then(result => console.log(result))
    
  • 删除多个 {}匹配所有

    Student.deleteMany({}).then(result => console.log(result))
    
更新文档
  • 更新单个

    Student.updateOne({sage:10},{sage:21}).then(result => console.log(result))
    
  • 更新多个

    Student.updateMany({sage:21},{sage:30}).then(result => console.log(result))
    

MongoDB增删改查操作

{}包括

  • type:属性的类型

  • required: true 必传字段 或者 required:[true,’ 填要输出的错误信息 ']

  • minlength:3 字符串最小长度

  • maxlength: 20 字符串最大长度

  • min: 2 数值最小为2

  • max: 100 数值最大为100

  • enum: [‘A’, ‘B’, ‘C’, ‘D’] 有该属性的字段要是数组里面的值才能插入数据库成功

  • trim: true 去除字符串两边的空格

  • default: 默认值

  • validate: 自定义验证器

validate:{
 	validateor:()=>{
   },
     message:' 填要输出的错误信息 '
}

集合关联

不同集合的数据之间是有关系的

再创建一个物品集合,belongto属性关联Student表中的_id字段。

var goodSchema=new mongoose.Schema({ 
	gname: { type: String } ,
    belongto: { type: mongoose.Schema.Types.ObjectId, ref: 'Student' }
});
var Goods = mongoose.model('Goods', goodSchema); 
Goods.create({
	gname:'js开发',
	belongto:'5fa4214a55544827940284ef'
}).then((err, result) => console.log(result));

通过添加populate()方法查看结果

Goods.find().populate('belongto').then(result => console.log(result));

结果:

ods.create({
	gname:'js开发',
	belongto:'5fa4214a55544827940284ef'
}).then((err, result) => console.log(result));

通过添加populate()方法查看结果

Goods.find().populate('belongto').then(result => console.log(result));

结果:

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值