MongoDB增删改查操作
创建集合
创建集合分为两步,一是对集合设定规则,二是创建集合,创建mongopse.Schema构造函数的实例即可创建集合。
创建文档
创建文档实际上就是向集合中插入数据
分为两步:
- 创建集合实例
- 调用实例对象下的sava方法将数据保存在数据库中
第一种方法 创建集合以及向集合中插入文档的步骤:
创建数据库后,要有具体的集合,在集合下面才是具体的数据。
在mongoose这个对象下面,有一个Schema构造函数,创建构造函数的实例就创建这个集合的规则,在里面创建一个对象,对象里规定的就是集合。
最后是创建集合,在mongoose对象下面有一个model方法用来创建集合,里面有两个参数,第一个参数代表集合名称,第二个参数代码集合规则。这个方法,返回的是一个构造函数。
想要插入数据,就实例化这个构造函数就可以。
实例对象有一个方法sava,作用是将创建的文档插入到数据库中
//mongoose第三方模块,用来操作数据库
const mongoose = require('mongoose');
//数据库链接
//playground为数据库的名字,此时在可视化软件里没有创建也没有哦关系,会自动创建
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true})
//链接成功
.then(() => console.log('链接成功'))
//链接失败
.catch(err => console.log(err, '链接失败'));
//创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
authour: String,
isPublish: Boolean
});
//使用规则去创建集合
const Course = mongoose.model('Course', courseSchema) //在数据里的集合的名字实际为courses
//创建文档
const course = new Course({
name: 'node.js基础',
author: '作者',
isPublish: true
})
//把数据插入到数据库中
course.save();
第二种方法 创建集合以及向集合中插入文档的步骤:
//mongoose第三方模块,用来操作数据库
const mongoose = require('mongoose');
//数据库链接
//playground为数据库的名字,此时在可视化软件里没有创建也没有哦关系,会自动创建
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true})
//链接成功
.then(() => console.log('链接成功'))
//链接失败
.catch(err => console.log(err, '链接失败'));
//创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
authour: String,
isPublish: Boolean
});
//使用规则去创建集合
const Course = mongoose.model('Course', courseSchema) //在数据里的集合的名字实际为courses
//第二种方式 插入文档
Course.create({
name: 'Java',
authour: 'a',
isPublish: false
}, (err, result) => {
console.log(err);
console.log(result);
})
关于数据库的所有操作都是异步操作
向数据库中导入数据
步骤:
先配置环境变量,将下面的地址(也就是mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中):
写到path环境中,配置环境的时候,在path后面的每一次配置用 ; 隔开
重启命令窗口
在命令行窗口,输入命令:
查询文档
find()返回的是一组数据,永远是数组,无论查询到几条文档
因为返回的是promise对象,所以可以用then()方法
//使用规则创建集合
const User = mongoose.model('User', userSchema);
//查询用户集合中的所有文档
User.find().then(result => console.log(result));
//查询id对应的文档
User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result));
findOne()返回的只有一条结果,默认返回当前集合中的第一条文档
User.findOne({name: '李四'}).then(result => console.log(result))
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result));
User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
查询 name,email字段但是不查询id字段:
User.find().select('name email -_id').then(result => console.log(result))
查询结果:
//根据年龄字段进行升序排列
User.find().sort('age').then(result => console.log(result))
//根据年龄字段进行降序排列
User.find().sort('-age').then(result => console.log(result))
可以做分页效果。