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)
}

转载于:https://www.cnblogs.com/hiramP/p/10724945.html

Node.js对MongoDB进行增删改查操作相关推荐

  1. MongoDB的增删改查操作

    前面介绍了MongoDB的基本概念与常见的操作,本文来重点分析下MongoDB的增删改查操作 文章目录 什么是"mongo" 新增操作 删除操作 更新操作 查询操作 Where语句 ...

  2. Node.js笔记-node.js连接MySQL与增删改查

    最近在看一个开源项目,项目用的是node.js,在此学习下他的连接mysql与增删改查. 安卓mysql包: npm install mysql 程序运行截图如下: D:\node\content\n ...

  3. JS对于JSON的增删改查操作

    使用JS对JSON数据的处理 最近项目中遇到需要对Json数据进行相关操作,比如增删改操作.之前没有操作过以为会挺难的,网上搜索下,发现还是比较简单的.相关的代码如下所示: <script ty ...

  4. servlet增删改查实例_SpringBoot系列(2)整合MongoDB实现增删改查(完整案例)

    自己本科时候一直使用的是Mysql,目前的课题组使用的是MongoDB,因此就花了一部分时间整理了一下,实现springboot与MongoDB的整合,并且实现基本的增删改查操作,从头到尾给出一个完整 ...

  5. SpringBoot操作MongoDB实现增删改查

    本篇博客主讲如何使用SpringBoot操作MongoDB. SpringBoot操作MongoDB实现增删改查 (1)pom.xml引入依赖 <dependency> <group ...

  6. SpringBoot增和MongoDB实现增删改查、复合查询

    SpringBoot增和MongoDB实现增删改查.复合查询 依赖 <dependency><groupId>org.springframework.boot</grou ...

  7. Node连接MySQL数据库进行基本的增删改查操作(一看就会)

    Node连接MySQL数据库进行基本的增删改查操作(一看就会) ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ❤️ ...

  8. python mongodb_python实现mongodb的增删改查

    python实现mongodb的增删改查 环境: 192.168.122.1 python 192.168.122.11 mongodb 一.安装pip,python的管理工具 官网下载: pip-1 ...

  9. MongoDB数据库增删改查基本使用

    MongoDB数据库增删改查基本使用 文章目录 MongoDB数据库增删改查基本使用 1.CRUD介绍 2.MongoDB数据库常用命令 3.MongoDB数据库显示命令 3.1.查询当前有多少个数据 ...

最新文章

  1. 利用歌词插件 让WMP活起来
  2. 提速20倍!谷歌AI发布TensorFlow 3D
  3. Android之SurfaceView(二)
  4. 傅里叶变换是用来做什么的,具体举例一下应用?
  5. Qt for Android调用原生接口打开相机拍照并存储照片
  6. 英文文章如何进行略读
  7. 目录的操作 c# 1614532397
  8. android与服务器交互总结(json,post,xUtils,Volley)
  9. BackgroundWorker 简单使用教程 多个线程的创建
  10. rup 裁剪_建筑企业信息系统RUP裁剪模型及其应用研究
  11. an error occurred while contacting the respository
  12. 程序员相亲大曝光 女方:做底层架构,什么时候升嘞!emmmm
  13. 管理员身份修改hosts文件
  14. labview中前面板如何设置背景图片
  15. write字符串python_Python-write()与writelines()和连接字符串
  16. Google爬虫如何抓取JavaScript的?
  17. 【JAVADS ——排序】
  18. 如何制作动态海报?教你一招在线合成GIF海报
  19. Oracle查询某个日期的周一到周日SQL语句
  20. 500 - 内部服务器错误。 您查找的资源存在问题,因而无法显示。

热门文章

  1. java 反射 内存_Java内存到反射入门
  2. python中sys模块有什么用_Python中模块之sys的功能介绍
  3. 怎么查看电脑内存和配置_电脑内存不足处理方法,电脑卡死处理方法。
  4. 【Pytorch神经网络理论篇】 30 图片分类模型:Inception模型
  5. 计算机视觉概述:视觉任务+场景领域+发展历程+典型任务
  6. [Kaggle] Spam/Ham Email Classification 垃圾邮件分类(RNN/GRU/LSTM)
  7. 天池 在线编程 插入五
  8. LeetCode 网易-1. 分割环(前缀和 + 哈希)
  9. LeetCode 684. 冗余连接(并查集)
  10. LeetCode 456. 132模式(逆序遍历+单调栈)