创建MongoDB集合
创建MongoDB集合数据
// 引入MongoDB第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库的连接
mongoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true, useUnifiedTopology: true })
// 连接成功
.then(() => console.log('数据库连接成功'))
// 连接失败
.catch(err => console.log(err,'数据库连接成功'))
// 创建集合规则
const courseSchema = new mongoose.Schema({
name: String,
author: String,
isPublished: Boolean
})
// 使用规则创建集合
// 参数一: 集合名称
// 参数二: 集合规则
const Course = mongoose.model('Course', courseSchema)
const course = new Course({
name: '名称',
author: '作者',
isPublished: true
})
course.save()
向数据库集合中插入文档数据
// 像集合中插入文档
// 参数一: 传入文档参数
// 参数二: 结果回调函数
Course.create({name: '名称1',author: '作者1',isPublished: false}, (err, result) => {
console.log(err)
})
MongoDB导入数据
Mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件(文件具体路径)
先要配置Mongoimport 的环境变量
查询数据
// 查询用户集合中的所有文档
Course.find().then(result => console.log(result))
// 查询集合中的指定条件的文档
Course.find({_id: '6006ad26774cbabfc45cdb4d'}).then(result => console.log(result))
// 或者 来返回一条文档(默认当前第一条数据)
Course.findOne({author: '作者'}).then(result => console.log(result))
其他查询条件
// 查询匹配大于 小于
Course.find({age: {$gt: 20,$lt: 30}}).then(result => console.log(result))
// 查询匹配包含
Course.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
// 选择要查询的字段()
Course.find().select('name email -id').then(result => console.log(result))
// 将查询到的数据升序排序|sort('-age')对数据进行降序排列
Course.find().sort('age').then(result => console.log(result))
// skip 跳过多少条数据 limit 限制查询数量 (分页使用)
Course.find().skip(2).limit(2).then(result => console.log(result))