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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值