MongoDB简介

MongoDB是一个开源的、文档型的NoSQL数据库程序。MongoDB将数据存储在类似JSON的文档中,操作起来更灵活方便。NoSQL数据库中的文档(documents)对应于SQL数据库中的一行。将一组文档组合在一起称为集合(collections),它大致相当于关系数据库中的表。

除了作为一个NoSQL数据库,MongoDB还有一些自己的特性:

  • 易于安装和设置
  • 使用BSON(类似于JSON的格式)来存储数据
  • 将文档对象映射到应用程序代码很容易
  • 具有高度可伸缩性和可用性,并支持开箱即用,无需事先定义结构
  • 支持MapReduce操作,将大量数据压缩为有用的聚合结果
  • 免费且开源
  • ......

连接MongoDB

在Node.js中,通常使用Mongoose库对MongoDB进行操作。Mongoose是一个MongoDB对象建模工具,设计用于在异步环境中工作。

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('Connected to MongoDB...'))
.catch( err => console.error('Could not connect to MongoDB... ', err));

Schema

Mongoose中的一切都始于一个模式。每个模式都映射到一个MongoDB集合,并定义该集合中文档的形状。

const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean
});

Model

模型是根据模式定义编译的构造函数,模型的实例称为文档,模型负责从底层MongoDB数据库创建和读取文档。

const Course = mongoose.model('Course', courseSchema);
const course = new Course({
name: 'Nodejs Course',
author: 'Hiram',
tags: ['node', 'backend'],
isPublished: true
});

新增(保存)一个文档

async function createCourse(){
const course = new Course({
name: 'Nodejs Course',
author: 'Hiram',
tags: ['node', 'backend'],
isPublished: true
}); const result = await course.save();
console.log(result);
} createCourse();

查找文档

async function getCourses(){
const courses = await Course
.find({author: 'Hiram', isPublished: true})
.limit(10)
.sort({name: 1})
.select({name: 1, tags:1});
console.log(courses);
}
getCourses();

使用比较操作符

async function getCourses(){
const courses = await Course
// .find({author: 'Hiram', isPublished: true})
// .find({ price: {$gt: 10, $lte: 20} })
.find({price: {$in: [10, 15, 20]} })
.limit(10)
.sort({name: 1})
.select({name: 1, tags:1});
console.log(courses);
}
getCourses();

使用逻辑操作符

  • or (或) 只要满足任意条件
  • and (与) 所有条件均需满足
async function getCourses(){
const courses = await Course
// .find({author: 'Hiram', isPublished: true})
.find()
// .or([{author: 'Hiram'}, {isPublished: true}])
.and([{author: 'Hiram', isPublished: true}])
.limit(10)
.sort({name: 1})
.select({name: 1, tags:1});
console.log(courses);
}
getCourses();

使用正则表达式

async function getCourses(){
const courses = await Course
// .find({author: 'Hiram', isPublished: true})
//author字段以“Hiram”开头
// .find({author: /^Hiram/})
//author字段以“Pierce”结尾
// .find({author: /Pierce$/i })
//author字段包含“Hiram”
.find({author: /.*Hiram.*/i })
.limit(10)
.sort({name: 1})
.select({name: 1, tags:1});
console.log(courses);
}
getCourses();

使用count()计数

async function getCourses(){
const courses = await Course
.find({author: 'Hiram', isPublished: true})
.count();
console.log(courses);
}
getCourses();

使用分页技术

通过结合使用 skip()limit() 可以做到分页查询的效果

async function getCourses(){
const pageNumber = 2;
const pageSize = 10;
const courses = await Course
.find({author: 'Hiram', isPublished: true})
.skip((pageNumber - 1) * pageSize)
.limit(pageSize)
.sort({name: 1})
.select({name: 1, tags: 1});
console.log(courses);
}
getCourses();

更新文档

先查找后更新

async function updateCourse(id){
const course = await Course.findById(id);
if(!course) return; course.isPublished = true;
course.author = 'Another Author'; const result = await course.save();
console.log(result);
}

直接更新

async function updateCourse(id){
const course = await Course.findByIdAndUpdate(id, {
$set: {
author: 'Jack',
isPublished: false
}
}, {new: true}); //true返回修改后的文档,false返回修改前的文档
console.log(course);
}

MongoDB更新操作符,请参考:https://docs.mongodb.com/manual/reference/operator/update/

删除文档

  • deleteOne 删除一个
  • deleteMany 删除多个
  • findByIdAndRemove 根据ObjectID删除指定文档
async function removeCourse(id){
// const result = await Course.deleteMany({ _id: id});
const course = await Course.findByIdAndRemove(id);
console.log(course)
}

Node.js对MongoDB进行增删改查操作的更多相关文章

  1. Scala对MongoDB的增删改查操作

    =========================================== 原文链接: Scala对MongoDB的增删改查操作 转载请注明出处! ==================== ...

  2. python 全栈开发,Day124(MongoDB初识,增删改查操作,数据类型,$关键字以及$修改器,"$"的奇妙用法,Array Object 的特殊操作,选取跳过排序,客户端操作)

    一.MongoDB初识 什么是MongoDB MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介 ...

  3. Node.js 实现 MySQL 数据库增删改查

    安装mysql $ npm isntall mysql 连接数据库 需要根据实际配置修改数据库用户名.及密码及数据库名 let mysql = require('mysql'); let connec ...

  4. Mongodb之增删改查操作

    一.创建一个数据库 在我们使用MongoDB数据库时引进了这样一个知识,“对于mongodb,使用了不存在的对象,就等于在创建这个对象”,所以创建数据库的操作就比较简单 在我们使用mysql数据库时u ...

  5. MongoDB基本增删改查操作-mongo shell

    基础 1.查看所有数据库: show dbs 2.选择数据库: use test 3.查看数据库中有哪些集合: show collections 如下图: 查询 1.查看集合中有哪些数据,其中abc为 ...

  6. MongoDB之增删改查(一)

    本文主要介绍MongoDB数据库增删改查操作. 增 mongoDB和其它关系型数据库一样,通过insert来添加数据到集合中去. db.collectionName.insert(内容) 显示数据库中 ...

  7. 【基础篇】js对本地文件增删改查--查

    前置条件: 1. 本地有安装node,点击传送门 项目目录: 1. msg.json内容 { "data": [ { "id": 1, "name&q ...

  8. 【基础篇】js对本地文件增删改查--改

    前置条件: 1. 本地有安装node,点击传送门 项目目录: 1. msg.json内容 { "data": [ { "id": 1, "name&q ...

  9. 【基础篇】js对本地文件增删改查--删

    前置条件: 1. 本地有安装node,点击传送门 项目目录: 1. msg.json内容 { "data": [ { "id": 1, "name&q ...

随机推荐

  1. layer.alert没有垂直居中

    经查找是因为 <!DOCTYPE html> 这句没有写在整个页面的最顶部,将其放在整个页面的第一行就可以了. ps:原理不是很清楚

  2. hdu-1036(格式题+精确度)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1036 心得:注意,要进行四舍五入的精确可以用+0.5实现. #include<iostream& ...

  3. 锋利的jQuery(第二版)学习总结

    通过对<锋利的jQuery>(第二版)一书的学习,发现此书讲解通俗易懂,是学习jQuery的一本很好的指导书,特作如下总结. 此书主要讲解了jQuery的常用操作,包括认识jQuery,j ...

  4. Windows下Python安装: requires numpy+mkl 和ImportError: cannot import name NUMPY_MKL

    最近写了一篇关于“微软开源分布式高性能GB框架LightGBM安装使用”的文章,有小伙伴安装Python环境遇到了问题.我个人也尝试安装了一下,确实遇到了很多问题."Windows7下pyt ...

  5. HDMI之HPD

    HDMI(19Pin)/DVI(16 pin)的功能是热插拔检测(Hot Plug Detect,HPD),这个信号将作为主机系统是否对HDMI/DVI是否发送TMDS信号的依据.HPD是从显示器输出 ...

  6. Nios内部RAM固化配置

    选择BSP Editor->Settings ->Advanced->hal->linker,然后勾选allow_code_at_reset.当然如果勾选enable_alt_ ...

  7. 【王者荣耀之IT大神版】1.1版本升级之“投降机制”

    版本:1.1 关于“投降机制”的理论基础与灵感来源于<微习惯>这本书. 简单来说,微习惯就是很小很小的习惯,比如说,每天做一个俯卧撑,每天看一页书等等.我们以前也许有过很多的计划,但却总是 ...

  8. Linux批量远程命令和上传下载工具

    https://github.com/eyjian/mooon/releases/tag/mooon-tools mooon_ssh:批量远程命令工具,在多台机器上执行指定命令 mooon_uploa ...

  9. Memory Allocation Error

    Memory allocation error happened when I tried to install MySQL 5.7.13 in my server, which has 2G mem ...

  10. codeblocks+SDCC开发51单片机

    说到51,大部分人都是用的是KEIL开发环境,但是KEIL是商业软件,我们一般人都用的是破解版的,如果用于商业就会收到法律诉讼.然而有一款很好的编译器专为51内核而存在.SDCC最大的有点就是开源免费 ...