MongoDB增删改查操作

MongoDB增删改查操作

一、创建集合

创建集合分为两步,一是对对集合设定规则 ,二是创建集合 ,创建mongoose.Schema构造函数的实例即可创建集合。

// 设定集合规则
 const courseSchema = new mongoose.Schema({
     name: String,
     author: String,
     isPublished: Boolean
 });
  // 创建集合并应用规则
 const Course = mongoose.model('Course', courseSchema); // courses
二、创建文档(插入数据)

创建文档实际上就是向集合中插入数据。分为两步:

  1. 创建集合实例。
  2. 调用实例对象下的save方法将数据保存到数据库中。
// 创建集合实例
 const course = new Course({
     name: 'Node.js course',
     author: '000',
     tags: ['node', 'backend'],
     isPublished: true
 });
  // 将数据保存到数据库中
 course.save();

使用Course下的create()方法向集合中插入数据。

Course.create({name: 'JavaScript基础', author: '001', isPublish: true}, (err, doc) => { 
     //  错误对象
    console.log(err);
     //  当前插入的文档
    console.log(doc);
});

由于Course.create()是一个可以返回promise对象的异步API,所以可以使用 .then()方法和 .catch()方法

Course.create({name: 'JavaScript基础', author: '002', isPublish: true})
      .then(doc => console.log(doc));
      .catch(err => console.log(err));
// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

// 创建集合规则
const courseSchema = new mongoose.Schema({
	name: String,
	author: String,
	isPublished: Boolean
});

// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema); // courses

// 向集合中插入文档
Course.create({name: 'Node', author: '路人甲', isPublished: true}, (err, result) => {
	 //  错误对象
	console.log(err)
	//  当前插入的文档
	console.log(result)
});
// 向集合中插入文档,Course.create()是一个可以返回promise对象的异步API,所以可以使用 .then()方法和 .catch()方法
Course.create({name: 'Javascript', author: '路人乙', isPublished: false})
		//  当前插入的文档
	  .then(result => console.log(result));
	   //  错误对象
      .catch(err => console.log(err));

在这里插入图片描述
在这里插入图片描述

三、mongoDB数据库导入数据

先导入一些数据方便后面查询的操作,使用mongoimport导入数据
语法:
mongoimport –d 数据库名称 –c 集合名称 --file 要导入的数据文件

要使用mongoimport必须要先将mongoimport添加到系统变量中。
步骤:
找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。

在这里插入图片描述

系统变量详细添加步骤:

注意:系统变量添加完成后必须重新启动一次命令行窗口该系统变量才能生效

在这里插入图片描述
在这里插入图片描述

接下来导入当前目录下的user.json文件
在这里插入图片描述
可以看到已经成功添加数据
在这里插入图片描述

四、查询文档

MongoDB 提供了 db.collection.find() 方法从集合中读取文档,其中提供了很多方法去查询数据

  • 指定查询过滤条件
  • 嵌入文档上的查询
  • 数组上的查询
  • 其他方法···

下面简单举例

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

// 创建集合规则
const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	email: String,
	password: String,
	hobbies: [String]
});

// 使用规则创建集合
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))
// 查询用户集合中年龄字段大于20并且小于40的文档
// User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))
// 查询用户集合中hobbies字段值包含足球的文档
// User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))
// 选择要查询的字段
// 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))
// 查询文档跳过前两条结果 限制显示3条结果
// User.find().skip(2).limit(3).then(result => console.log(result))
五、删除文档

MongoDB中提供了以下方法来删除文档:

删除的方法解释说明
db.collection.remove()删除单个文件或匹配指定过滤器的所有文件。
db.collection.deleteOne()即使多个文件可以匹配指定过滤器,也只删除第一个文件。
db.collection.deleteMany()删除所有匹配指定过滤条件的文档.
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
User.findOneAndDelete({}).then(result => console.log(result))
// 删除多条文档
User.deleteMany({}).then(result => console.log(result))
六、更新文档

MongoDB提供如下方法更新集合中的文档:

更新文档的方法解释说明
db.collection.updateOne()即使可能有多个文档通过过滤条件匹配到,但是也最多也只更新一个文档。
db.collection.updateMany()更新所有通过过滤条件匹配到的文档.
db.collection.replaceOne()即使可能有多个文档通过过滤条件匹配到,但是也最多也只替换一个文档。
db.collection.update()即使可能有多个文档通过过滤条件匹配到,但是也最多也只更新或者替换一个文档。

默认情况下, db.collection.update() 只更新 一个 文档。要更新多个文档,请使用 multi 选项。

这些方法接收(如下)参数:

  • 过滤条件文档—-决定更些哪些文档。 这些 文档过滤查询 使用和读操作相同的语法:

  • 查询过滤文档 能够用 : 表达式指定相等条件并以此选出所有包含有指定 的 的文档:

{ <field1>: <value1>, ... }
  • 查询过滤文档 能使用以下 ref:查询操作符 来指定查询条件:
{ <field1>: { <operator1>: <value1> }, ... }
  • 更新文档—-指定要执行的修改或替换文档—完全替换匹配文档(除了 _id 字段)

  • 选项文档

// 如果匹配了多条文档, 只会更新匹配成功的第一条文档
User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))
// 找到要更新的文档并且更新
User.updateMany({}, {age: 300}).then(result => console.log(result))
七、mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就则输入插入失败。

  • required: true 必传字段
  • minlength:3 字符串最小长度
  • maxlength: 20 字符串最大长度
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’]
  • trim: true 去除字符串两边的空格
  • validate: 自定义验证器
  • default: 默认值

获取错误信息:error.errors[‘字段名称’].message

代码示例

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

const postSchema = new mongoose.Schema({
	title: {
		type: String,
		// 必选字段
		required: [true, '请传入文章标题'],
		// 字符串的最小长度
		minlength: [2, '文章长度不能小于2'],
		// 字符串的最大长度
		maxlength: [5, '文章长度最大不能超过5'],
		// 去除字符串两边的空格
		trim: true
	},
	age: {
		type: Number,
		// 数字的最小范围
		min: 18,
		// 数字的最大范围
		max: 100
	},
	publishDate: {
		type: Date,
		// 默认值
		default: Date.now
	},
	category: {
		type: String,
		// 枚举 列举出当前字段可以拥有的值
		enum: {
			values: ['html', 'css', 'javascript', 'node.js'],
			message: '分类名称要在一定的范围内才可以'
		}
	},
	author: {
		type: String,
		validate: {
			validator: v => {
				// 返回布尔值
				// true 验证成功
				// false 验证失败
				// v 要验证的值
				return v && v.length > 4
			},
			// 自定义错误信息
			message: '传入的值不符合验证规则'
		}
	}
});

const Post = mongoose.model('Post', postSchema);

Post.create({title:'aa', age: 60, category: 'java', author: 'bd'})
	.then(result => console.log(result))
	.catch(error => {
		// 获取错误信息对象
		const err = error.errors;
		// 循环错误信息对象
		for (var attr in err) {
			// 将错误信息打印到控制台中
			console.log(err[attr]['message']);
		}
	})
八、集合关联

通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。

  • 使用id对集合进行关联
  • 使用populate方法进行关联集合查询

在这里插入图片描述

代码示例

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true})
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

// 用户集合规则
const userSchema = new mongoose.Schema({
	name: {
		type: String,
		required: true
	}
});
// 文章集合规则
const postSchema = new mongoose.Schema({
	title: {
		type: String
	},
	author: {
		type: mongoose.Schema.Types.ObjectId,
		ref: 'User'
	}
});
// 用户集合
const User = mongoose.model('User', userSchema);
// 文章集合
const Post = mongoose.model('Post', postSchema);

// 创建用户
// User.create({name: 'itheima'}).then(result => console.log(result));
// 创建文章
// Post.create({titile: '123', author: '5c0caae2c4e4081c28439791'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result))

想了解更多详细信息请访问:

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gxhlh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值