NoteZ_技术博客 NoteZ_技术博客
🏠 首页
  • 📚 Web技术
  • 📋 Npm笔记
  • 📑 Markdown
  • 📄 Git笔记
  • 📝 Nginx文档
  • 📓 Linux文档
  • 📖 技术文档
  • 📜 其他文档
  • 🧊 NodeJs
  • 🎡 Express
  • 🔥 Rust
  • 🎉 Koa2
  • 🍃 MongoDB
  • 🐬 MySql
  • 🥦 Oracle
  • 🍁 Python
  • 🍄 JavaScript
  • 🌰 CSS
  • 🧄 HTML
  • 🥑 Canvas
  • 🌽 Nuxt
  • 🍆 React
  • 🥜 Vue
  • 🧅 TypeScript
  • 🌶️ AI
  • 📘 分类
  • 📗 标签
  • 📙 归档
⚜️ 在线编辑 (opens new window)
  • 📁 站点收藏
  • 📦 前端组件库
  • 📊 数据可视化
  • 🌈 开源插件
  • 🎗️ 关于我
  • 🔗 友情链接
GitHub (opens new window)

NoteZ_技术博客

前端界的小学生
🏠 首页
  • 📚 Web技术
  • 📋 Npm笔记
  • 📑 Markdown
  • 📄 Git笔记
  • 📝 Nginx文档
  • 📓 Linux文档
  • 📖 技术文档
  • 📜 其他文档
  • 🧊 NodeJs
  • 🎡 Express
  • 🔥 Rust
  • 🎉 Koa2
  • 🍃 MongoDB
  • 🐬 MySql
  • 🥦 Oracle
  • 🍁 Python
  • 🍄 JavaScript
  • 🌰 CSS
  • 🧄 HTML
  • 🥑 Canvas
  • 🌽 Nuxt
  • 🍆 React
  • 🥜 Vue
  • 🧅 TypeScript
  • 🌶️ AI
  • 📘 分类
  • 📗 标签
  • 📙 归档
⚜️ 在线编辑 (opens new window)
  • 📁 站点收藏
  • 📦 前端组件库
  • 📊 数据可视化
  • 🌈 开源插件
  • 🎗️ 关于我
  • 🔗 友情链接
GitHub (opens new window)
  • Express

  • Koa2

  • MongoDB

    • linux 下 mongodb 的安装及配置
    • MongoDB 备份(mongodump)与恢复(mongorestore)
    • MongoDB 插入(insert)数据的正确方法
    • MongoDB 数据库
    • MongoDB 数据库设置账号密码(权限)
    • MongoDB集合数据查询总结
    • Mongoose 动态给 Schema 添加属性
    • Mongoose 数据验证
    • NodeJs 连接操作 MongoDB 数据库
      • 安装 MongoDB 驱动
      • 连接创建数据库
      • 插入数据操作
      • 查询数据操作
      • 更新数据操作
      • 删除数据操作
      • 创建数据索引
        • 简单索引
        • 复合索引
        • 全文索引
      • 用户的创建、删除和修改
    • Node下使用MongoDB 数据库多条件模糊查询
    • 使用 JS 操作 MongoDB 命令
    • 如何解决Mongodb大数据量分页查询效率问题
    • 给MongoDB数据库bin目录添加工具集
  • MySql

  • NodeJs

  • Oracle

  • Rust

  • Python

  • 后端开发
  • MongoDB
NoteZ
2020-03-19
目录

NodeJs 连接操作 MongoDB 数据库

# 安装 MongoDB 驱动

npm install mongoose --save
1

# 连接创建数据库

const mongoose = require('mongoose');
mongoose.connect(`mongodb://username:password@localhost:27017/test?authSource=admin`, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('数据库连接成功!');
        // db.close(); //关闭数据库
    }
});
let Schema = mongoose.Schema;
let gather = new Schema({
    name: {
        type: String,
        default: ""
    },
    type: {
        type: String,
        default: ""
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 插入数据操作

插入一条数据条数据,使用 insertOne():

gather.insertOne({name:'sdwe'} , function (err, res) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('插入成功!');
    }
});
1
2
3
4
5
6
7

插入多条数据条数据,使用 insertMany():

let data = [
    {name:'sdwe1'},
    {name:'sdwe2'}
]
gather.insertMany(data , function (err, res) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('插入成功!');
        console.log("插入的文档数量为: " + res.insertedCount);
    }
});

1
2
3
4
5
6
7
8
9
10
11
12
13

# 查询数据操作

查询单条数据,使用 findOne():

gather.findOne({name:'sdwe'} , function (err, result) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('查询成功!');
        console.log(result);
    }
});

// 或者
gather.findById({_id:'ssdf09sdif9dsf8h'} , function (err, result) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('查询成功!');
        console.log(result);
    }
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

查询多条数据,使用 find():

gather.find({name:'sdwe'} , function (err, result) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('查询成功!');
        console.log(result);
    }
});
1
2
3
4
5
6
7
8

条件查询数据,使用 find():

gather.find({name: {$regex: new RegExp('sdwe', 'gi')},type:'1',mark:/学/,$or: [{by: "sfer"},{title: "rwe343df"}]}, function (err, result) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('查询成功!');
        console.log(result);
    }
});
1
2
3
4
5
6
7
8

筛选查询嵌套数据,使用 find():

gather.find({"a.b":"HTML"}, {name:true,"a.b":true,_id:false}, function (err, result) { //这里的false和true,也可以用0和1表示
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('查询成功!');
        console.log(result);
    }
});
1
2
3
4
5
6
7
8
操作 格式 范例 RDBMS中的类似语句
等于 {key:value} db.gather.find({"by":"sdsd"}) where by = 'sdsd'
小于 {key:{$lt:value}} db.gather.find({"likes":{$lt:50}}) where likes < 50
小于或等于 {key:{$lte:value}} db.gather.find({"likes":{$lte:50}}) where likes <= 50
大于 {key:{$gt:value}} db.gather.find({"likes":{$gt:50}}) where likes > 50
大于或等于 {key:{$gte:value}} db.gather.find({"likes":{$gte:50}}) where likes >= 50
不等于 {key:{$ne:value}} db.gather.find({"likes":{$ne:50}}) where likes != 50

使用 find() 来查找数据, find() 可以返回匹配条件的所有数据。 如果未指定条件,find() 返回集合中的所有数据。

# 更新数据操作

更新单条数据,使用 updateOne():

gather.updateOne({name:'sdwe'} ,{$set: { name:'sdjnds' }}, function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('更新成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

更新多条数据,使用 updateMany():

gather.updateMany({name:'sdwe'} ,{$set: { name:'sdjnds' }} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('更新成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

比较安全的更新数据,使用 findAndModify() 的性能是没有直接使用 db.collections.update 的性能好,但是在实际工作中都是使用它,毕竟要商用的程序安全性还是比较重要的,如下代码:

let myModify = {
    findAndModify:"col",
    query:{name:'adsd'},
    update:{$set:{age:16}},
    new:true    //更新完成,需要查看结果,如果为false不进行查看结果
}
let Result = gather.runCommand(myModify);
console.log(Result);
1
2
3
4
5
6
7
8

findAndModify属性值:

  • query:需要查询的条件/文档
  • sort: 进行排序
  • remove:[boolean]是否删除查找到的文档,值填写true,可以删除。
  • new:[boolean]返回更新前的文档还是更新后的文档。
  • fields:需要返回的字段
  • upsert:没有这个值是否增加。

更新嵌套内容(内嵌文档)

gather.updateMany({name:'sdwe'} ,{$set:{"a.b":'dsdewe'}} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('更新成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

删除一个key值和键,使用 $unset 操作符

gather.updateMany({name:'sdwe'} ,{$unset:{name:''}} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('更新成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

对数字进行计算,使用 $inc 操作符

它是对value值的修改,但是修改的必须是数字,字符串是不起效果的。我们现在要对sdwe的年龄减去2岁,就可以直接用$inc来操作,例如:

gather.updateOne({name:'sdwe'} ,{$inc:{age:-2}} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('更新成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

# 删除数据操作

删除单条数据,使用 deleteOne():

gather.deleteOne({name:'sdwe'} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('删除成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

删除多条数据,使用 deleteMany():

gather.deleteMany({name:'sdwe'} , function (err, data) {
    if (err) {
        console.log('Connection Error:' + err);
    } else {
        console.log('删除成功!');
        console.log(data);
    }
});
1
2
3
4
5
6
7
8

# 创建数据索引

# 简单索引

gather.ensureIndex({name:1});
1

查看现有索引

gather.getIndexes();
1

# 复合索引

两个索引同时查询

let startTime = new Date().getTime();

gather.find({name:'ssdssfreferge',type:565509});

let runTime = new Date().getTime() - startTime;
console.log('[Demo]this run time is '+runTime+'ms');
// print('[Demo]this run time is '+runTime+'ms');
1
2
3
4
5
6
7

指定索引查询(hint)

gather.find({name:'ssdssfreferge',type:565509}).hint({type:1});
1

删除索引,当索引性能不佳或起不到作用时,我们需要删除索引,删除索引的命令是 dropIndex()

gather.dropIndex('type_1');//索引的唯一ID
1

这里需要注意的是删除时填写的值,并不是我们的字段名称(key),而是我们索引查询表中的name值。

# 全文索引

全文索引适合大篇幅的文章中搜索关键词,建立全文索引:

gather.ensureIndex({contextInfo:'text'}) // contextInfo 为文章字段
gather.find({$text:{$search:"keyword"}}) // 单个词,查找数据中有programmer的数据
gather.find({$text:{$search:"programmer family diary drink"}}) // 多个词,查找数据中有programmer,family,diary,drink的数据
gather.find({$text:{$search:"programmer family diary -drink"}}) // 不查找出来有drink这个单词的记录,我们可以使用“-”减号来取消
gather.find({$text:{$search:"\"love PlayGame\" drink"}})
1
2
3
4
5
  • $text:表示要在全文索引中查东西。
  • $search:后边跟查找的内容。

注意

  1. 数据不超万条时,不需要使用索引。性能的提升并不明显,而大大增加了内存和硬盘的消耗。

  2. 查询数据超过表数据量30%时,不要使用索引字段查询。实际证明会比不使用索引更慢,因为它大量检索了索引表和我们原表。

  3. 数字索引,要比字符串索引快的多,在百万级甚至千万级数据量面前,使用数字索引是个明确的选择。

  4. 把你经常查询的数据做成一个内嵌数据(对象型的数据),然后集体进行索引。

# 用户的创建、删除和修改

常用命令

  • use admin:进入我们的admin库
  • show collections:查看数据库中的集合

创建用户可以用db.createUser方法来完成

db.createUser({
    user:"sdffs",
    pwd:"123456",
    customData:{
        name:'zsfascas',
        email:'web0432@126.com',
        age:18,
    },
    roles:[
        {
            role:"readWrite",
            db:"company"
        },
        'read'
    ]
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

内置角色

  • 数据库用户角色:read、readWrite;
  • 数据库管理角色:dbAdmin、dbOwner、userAdmin;
  • 集群管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManage;
  • 备份恢复角色:backup、restore;
  • 所有数据库角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase
  • 超级用户角色:root
  • 内部角色:__system 查找用户信息
db.system.users.find()
1

删除用户

db.system.users.find()
1

建权

db.auth("sda","123456")
1

启动建权

mongod --auth
1

启动后,用户登录只能用用户名和密码进行登录,原来的mongo形式链接已经不起作

#MongoDB#NodeJs
上次更新: 2024/01/30, 00:35:17
Mongoose 数据验证
Node下使用MongoDB 数据库多条件模糊查询

← Mongoose 数据验证 Node下使用MongoDB 数据库多条件模糊查询→

最近更新
01
Gitea数据备份与还原
03-10
02
Linux 中使用 rsync 同步文件目录教程
03-10
03
Linux 使用 rsync 互相传输同步文件的简单步骤
03-08
更多文章>
Theme by Vdoing | Copyright © 2019-2025 NoteZ,All rights reserved | 冀ICP备2021027292号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式