开启mongoDB服务:net start mongoDB
关闭mongoDB服务:net stop mongoDB
连接mongodb
const mongooes = require('mongoose'); //导入mongoDB模块 mongooes.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('数据库已连接'); }) .catch((err) => { console.log(err, '数据库连接失败'); });
创建集合(集合相当于关系型数据库中的表)
//使用规则创建集合 const courseSchema = new mongooes.Schema({ //创建规则 name: String, author: String, isPublished: Boolean }); //创建集合 //courses 第一个参数是集合名,在代码中首字母为大写,在数据库中则为首字母小写,并后面加一个s因为集合中会存放多条文档 //返回值是一个构造函数,用来构造实例 const Course = mongooes.model('Course', courseSchema);
创建文档(第一种方法)
//创建集合实例 const course = new Course({ name: 'node.js', author: '老师', isPublished: true }); course.save(); //保存集合实例
创建文档(第二种方法)
Course.create({ name: 'java', author: '虎', isPublished: true }) //create方法返回的是一个promise .then((doc) => { console.log(doc); }) .catch(err => console.log(err));
数据库导入数据:mongoimport -d playground -c users -file user.json //file前面有两个--
mongoimport –d 数据库名称 –c 集合名称 ––file 要导入的数据文件
查找文档
Course.find().then(dec => console.log(dec));//查找集合中所有的文档,find返回的是一个数组
Course.find({name: 'node.js基础'}).then(result => console.log(result)) // 根据条件查找文档,参数是一个对象,存放着查询条件
Course.findOne({name: 'node.js基础'}).then(result => console.log(result)) // 根据条件查找文档,findOne()返回的是一个数据,如果有多条数据则返回第一条数据
User.find({age: {$gt: 20, $lt: 50}}).then(result => console.log(result))// 匹配大于 小于
User.find({hobbies: {$in: ['敲代码']}}).then(result => console.log(result))// 匹配包含
User.find().select('name email').then(result => console.log(result))// 选择要查询的字段
User.find().sort('age').then(result => console.log(result))// 将数据按照年龄进行排序,默认是按照从小到大的顺序排列,加上负号就是从大到小排序
User.find().skip(2).limit(2).then(result => console.log(result))// skip 跳过多少条数据 limit 限制查询数量
删除文档
// 删除单个,返回值是删除的数据 Course.findOneAndDelete({}).then(result => console.log(result)) // 删除多个,返回值是一个对象,ok属性表示是否操作成功,n表示删除的个数 User.deleteMany({}).then(result => console.log(result))