MongoDB是一个开源的著名文档数据库,其灵活的数据模型和易用的API让我们在处理海量数据时更加高效,其中CRUD操作是MongoDB中最为常见的操作,本文将对CRUD操作进行深入的讲解,并附带两条示例.
CRUD指的是Create(创建)、Read(读取)、Update(更新)和Delete(删除)操作,是MongoDB中最常用的操作.
Create操作即数据的添加操作,在MongoDB中使用insertOne()或insertMany()方法实现数据的添加操作,示例代码如下所示:
// 示例1: 添加一条数据
db.collection('users').insertOne({
name: 'Jack',
age: 20,
email: 'jack@example.com'
}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
// 示例2: 添加多条数据
db.collection('users').insertMany([{
name: 'Tom',
age: 18,
email: 'tom@example.com'
}, {
name: 'Lucy',
age: 22,
email: 'lucy@example.com'
}]).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
Read操作即数据的读取操作,在MongoDB中使用find()方法实现数据的查询操作,可以通过find()方法的参数进行数据的筛选,示例代码如下所示:
// 示例1: 获取所有数据
db.collection('users').find().toArray((error, users) => {
if (error) throw error
console.log(users)
})
// 示例2: 获取年龄大于等于18岁的数据
db.collection('users').find({
age: { $gte: 18 }
}).toArray((error, users) => {
if (error) throw error
console.log(users)
})
Update操作即数据的更新操作,在MongoDB中使用updateOne()或updateMany()方法实现数据的更新操作,示例代码如下所示:
// 示例1: 更新一条数据
db.collection('users').updateOne({
name: 'Jack'
}, {
$set: { age: 21 }
}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
// 示例2: 更新所有数据
db.collection('users').updateMany({}, {
$inc: { age: 1 }
}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
Delete操作即数据的删除操作,在MongoDB中使用deleteOne()或deleteMany()方法实现数据的删除操作,示例代码如下所示:
// 示例1: 删除一条数据
db.collection('users').deleteOne({
name: 'Jack'
}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
// 示例2: 删除所有数据
db.collection('users').deleteMany({}).then(result => {
console.log(result)
}).catch(error => {
console.log(error)
})
// 创建留言板数据模型
const messageSchema = new mongoose.Schema({
name: String,
content: String
})
// 创建留言板数据模型对应的集合
const Message = mongoose.model('Message', messageSchema)
// 添加留言
app.post('/api/messages', (req, res) => {
const message = new Message(req.body)
message.save(err => {
res.send('留言已删除')
})
})
// 创建博客数据模型
const postSchema = new mongoose.Schema({
title: String,
content: String,
author: String,
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now }
})
// 创建博客数据模型对应的集合
const Post = mongoose.model('Post', postSchema)
// 添加博客
app.post('/api/posts', (req, res) => {
const post = new Post(req.body)
post.save(err => {
res.send('博客已删除')
})
})
以上就是土嘎嘎小编为大家整理的mongoDB中CRUD的深入讲解相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!