MongoDB基础操作入门笔记
MongoDB是一种文档导向的非关系型数据库系统。
文档数据库也被称为NoSQL。
与关系型数据库不同,它只需将JSON对象保存到MongoDB中,非常简单。
打开方式
$ mongod
waiting for connections on port 27017
在使用数据库时,通常保持其处于运行状态。
在结束时务必使用Ctrl+C来确认是否成功关闭!
当安装了类似PSequel的应用程序MongoDB Compass,可以方便地查看数据库的内容,非常方便。
蒙古鼠
MongoDB已经提供了建模工具,用户可以定义和操作模型。
npm i mongoose
安装Mongoose
下面是使用node的情况。
const mongoose = require('mongoose');
// localhostでの実行。Databaseを自動で作ってくれます
mongoose
.connect('mongodb://localhost/playground', { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB...'))
.catch(err => console.error('Could not connect to the DB', err));
当在终端上使用 node index.js 运行时,会显示出”已连接到 MongoDB…”的成功连接消息。
连接MongoDB
// Schemaの作成
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean
});
// Model (大文字・単数)
const Course = mongoose.model('Course', courseSchema);
创建数据
async function createCourse() {
const course = new Course({
name: 'Node.js',
author: 'John',
tags: ['node', 'javascript'],
// dateは自動で生成されるので記載なし
isPublished: true
});
const result = await course.save();
console.log(result);
}
createCourse();
请注意,虽然这里提到了”course”一词,但这些仅仅是示例。
获取数据
// GET
async function getCourses() {
const courses = await Course
.find({ author: 'john', isPublished: true })
.limit(10)
.sort({ name: 1 })
.select({ name: 1, tags: 1 });
console.log(courses);
}
getCourses();
数据更新
async function updateCourse(id) {
// idで、対象のコースを見つける
const course = await Course.findById(id);
if (!course) return;
// Object
course.isPublished = true;
course.author = 'Another Author';
const result = await course.save();
console.log(result);
}
updateCourse('ここにMongoのObject Idを');
通过另一种方法,也可以进行更新。
async function updateCourse(id) {
// idで、対象のコースを見つける
const course = await Course.update(
{ _id: id },
{
$set: {
author: 'Another Author',
isPublished: false
}
}
);
console.log(course);
}
updateCourse('ここにMongoのObject Idを');
数据删除
async function removeCourse(id) {
const result = await Course.deleteOne({ _id: id });
console.log(result);
}
removeCourse('ここにMongoのObject Idを');
但是除了使用deleteOne方法之外,还有其他许多方法,例如deleteMany等等,所以请确保在学习之前查阅此文档!
心得体会
由于MongoDB经常被用作称为MEAN Stack或MERN Stack的技术组合,所以它的教程非常齐全,学习资源非常丰富,这是学习初期的一个优势。
如果有任何错误,请不吝指正留言,不胜感激!