文章目录
- 1. 概述 - 高性能、无模式、开源的文档数据库
- 2. 安装
- 3. 语法
1. 概述 - 高性能、无模式、开源的文档数据库
选择场景 = 满足下面一个即可选择使用MongoDB
0. 解决高并发、高存储、高可扩展、高可用性
1. 应用不需要事务及复杂join支持
2. 新应用,需求会变,数据模型无法确定,想快速迭代开发
3. 应用需要2000-3000以上的读写QPS(更高也可以)
4. 应用需要TB甚至PB级别数据存储
5. 应用要求存储的数据不丢失
6. 应用需要99.999%高可用
7. 应用需要大量的地理位置查询、文本查询
概念
针对关系型数据库概念的理解
SQL术语/概念 | MongoDB术语/概念 | 解释/说明 |
---|---|---|
database | database | 数据库 |
table | collection | 数据库表/集合 |
row | document | 数据记录行/文档 |
column | field | 数据字段/域 |
index | index | 索引 |
table joins | 表连接,MongoDB不支持 | |
嵌入文档 | MongoDB通过嵌入式文档来替代多表连接 | |
primary key | primary key | 主键,MongoDB自动将_id字段设置为主键 |
数据类型
数据类型 | 描述 | 举例 |
---|---|---|
字符串 | UTF-8字符串都可表示为字符串类型的数据 | {“x”:“foobar”} |
对象id | 对象id是文档的12字节的唯一ID | {“X”:Objectld()} |
布尔值 | 真或者假:true或者false | {“x”:true) |
数组 | 值的集合或者列表可以表示成数组 | {“x”:[“a”,“b”,"c]} |
32位整数 | 类型不可用。JavaScript仅支持64位浮点数,所以32整数会自动转换 | shell是不支持该类型的,shell中默认会转换成64位浮点数 |
64位整数 | 不支持这个类型。shel会使用一个特殊的内嵌文档来显示64位整数 | (x:3.14159,y:3) |
null | 表示空值或者未定义的对象 | {“x”:null) |
undefined | 文档中也可以使用未定义类型 | {“x”:undefined} |
符号 | shell不支持,shell会将数据库中的符号类型的数据自动转换成字符串 | |
正则表达式 | 文档中可以包含正则表达式,采用/avaScip的正则表达式语法 | {x:/fobar/i} |
代码 | 文档中还可以包含avaScript代码 | {"x”:function){/………/} |
二进制数 | 二进制数据可以由任意字节的串组成,不过shel中据无法使用 | |
最大值/最小值 | BSON包括一个特殊类型,表示可能的最大值。shell中没有这个类型。 |
2. 安装
Windows
下载位置
千万千万注意:不要沟那个选项,要不然安装进度条运行的很慢
环境变量配置
//1. 新启一个CMD窗口 == 用于启动MongoDB服务
mongod
//2. 上述启动成功后在新起一个CMD窗口,用于操作MongoDB里面的数据
mongo
当然使用Navicat也可以查MongoDB的数据
3. 语法
DDL - 数据定义操作
语法使用
// 查看系统中含有数据的所有库名
show databases
show dbs
// 切换当前操作的库
use 数据库名
// 查看当前用户所在的库
db
// 查看当前库中含有有数据的集合名(表名)
show collections
show tables;
//删除当前用户所use的数据库
db.dropDatabase();
//删表
db.表名.drop();
//显示创表
db.createCollection("表名")
创表 - 有限制表、无限制表
//创无容量限制的表
db.createCollection(表名)
//开启capped必须设置表最大大小size
//创有容量限制的表 == 表最大大小为5M,一旦超过则删除旧的记录以存新记录
db.createCollection(表名, { capped:true, size: 5242880 })
//创有容量限制的表 == 表最大大小为5M且记录数最多只能两条,一旦超过表容量或者最大记录数则删除旧的记录以存新记录
db.createCollection("test2", {capped:true, size: 5242880, max: 2})
//删表
db.表名.drop();
内置表查看 - admin、local、config
//作用:root权限、用户添加入此数据库自动继承mongo所有权限
show dbs;
use admin;
show collections;
db.system.version.find();
//作用:此库数据永远不会被删除
show dbs;
use config;
show collections;
db.system.sessions.find();
// 作用:Mongo分片时,用于保存分片信息
show dbs;
use local;
show collections;
db.startup_log.find();
index索引 - 提升查询效率
//查看此表全部索引
db.表名.getIndexes();
//创建索引 1升序 -1降序
db.表名.createIndex({属性名:1,属性名2:-1}, {name:"索引名"})
//示例
db.article_tag.createIndex({
id: 1,
tag_name: - 1
})
//删除索引
db.表名.dropIndex("索引名");
//删除全部索引,除了_id列的主键索引没删
db.表名.dropIndexes();
explain执行计划 - 分析DQL查询语句
参数解释
//缺乏executionStats节点显示
db.test.find({name: "lrc"}).explain();
//更加详细的执行信息
db.test.find({name: "lrc"}).explain({executionStats:1});
参数 | 含义 |
---|---|
plannerVersion | 查询计划版本 |
namespace | 要查询的集合 |
indexFilterSet | 是否使用索引 |
parsedQuery | 查询条件,此处为x=1 |
winningPlan | 最佳执行计划 |
stage | 查询方式,常见的有COLLSCAN/全表扫描、IXSCAN/索引扫描、FETCH/根据索引去检索文档、SHARD_MERGE/合并分片结果、IDHACK/针对_id进行查询 |
filter | 过滤条件 |
direction | 搜索方向 |
rejectedPlans | 拒绝的执行计划 |
serverInfo | MongoDB服务器信息 |
executionSuccess | 是否执行成功 |
nReturned | 返回的结果数 |
executionTimeMillis | 执行耗时 |
totalKeysExamined | 索引扫描次数 |
totalDocsExamined | 文档扫描次数 |
executionStages | 这个分类下描述执行的状态 |
stage | 扫描方式,具体可选值与上文的相同 |
nReturned | 查询结果数量 |
executionTimeMillisEstimate | 预估耗时 |
works | 工作单元数,一个查询会分解成小的工作单元 |
advanced | 优先返回的结果数 |
docsExamined | 文档检查数目,与totalDocsExamined一致 |
使用
查询语句.explain
//示例
db.article_tag.find({
"user_id": "c08d391e02bc11eb9416b42e99ea3e69",
"tag_name":"接口java4"
}).explain()
查看表索引信息
示例查询分析 == 请关系winningPlan节点
Navicat的查询解析
DML-文档操作-CRUD(Create、Read、Update、Delete)
增加文档Create - 每插入一条如果没主动设置则自动增加属性【_id】
//插入单条或多条数据、多条则传数组进去即可
db.数组名(表名).insert(JSON数据)
//插入单条数据
db.数组名(表名).insertOne(JSON数据)
//插入多条数据
db.数组名(表名).insertMany([JSON数据1,JSON数据2,...............])
//批量插入数据1 == 速度慢 == 执行20000遍插入SQL
for(var i = 0; i<20000; i++) {
db.数组名(表名).insert({num: i, mark:"测试"})
}
//示例
for(var i = 0; i<20000; i++) {
db.test.insert({num: i, mark:"测试"})
}
//批量插入数据2 == 速度更快 == 仅执行一遍插入SQL
var result = [];
for(var i = 0; i<20000; i++) {
result.push({num: i, mark:"测试"+i});
}
db.数组名(表名).insertMany(result);
//示例
var result = [];
for(var i = 0; i<20000; i++) {
result.push({num: i, mark:"测试"+i});
}
db.test.insertMany(result);
批量插入数据成功1
批量插入数据成功2
示例数据添加
db.book.insertMany([
{
"author": "理查德·巴赫",
"country": "美国",
"createTime": "2021-01-31 21:25:16",
"downloadUrl": "http://qiniuyun.linruchang.work/f91115354c404386bc23139aa946e953.mobi",
"fileType": "mobi",
"id": "0015ac644213f7db45d63e09c6403395",
"isDel": 0,
"isViolation": 0,
"name": "海鸥乔纳森",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "易富贤",
"country": "中国",
"createTime": "2021-01-20 22:16:50",
"downloadUrl": "http://qiniuyun.linruchang.work/c03a1f0a93a248c0ad74fbaa752ecab7.pdf",
"fileType": "pdf",
"id": "02b65ed26a1e0938865bd76b0790ac12",
"isDel": 0,
"isViolation": 0,
"name": "(社会)大国空巢",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "戴维·艾伦",
"country": "美国",
"createTime": "2021-02-01 15:57:21",
"downloadUrl": "http://qiniuyun.linruchang.work/90cb6976f97f463396dfb17c3990ef4b.pdf",
"fileType": "pdf",
"id": "033ffd2017844eef10c5733cf8e6c375",
"isDel": 0,
"isViolation": 0,
"name": "搞定(全三册)",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "王沪宁",
"country": "中国",
"createTime": "2021-01-23 09:30:05",
"downloadUrl": "http://qiniuyun.linruchang.work/64bf830eebaa4d74b8d1bbe210488100.pdf",
"fileType": "pdf",
"id": "05a5bec81474ded3683f1a5c900ff350",
"isDel": 0,
"isViolation": 0,
"name": "美国反对美国",
"readingFeeling": "只为分享\n",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "东野圭吾",
"country": "日",
"createTime": "2021-01-20 22:20:33",
"downloadUrl": "http://qiniuyun.linruchang.work/b50543dfbda742439e0e49dac87beafe.mobi",
"fileType": "mobi",
"id": "05e63b6fae427c1ba38279bfc30fb5e6",
"isDel": 0,
"isViolation": 0,
"name": "秘密",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "阿来",
"country": "中国",
"createTime": "2021-01-24 01:33:32",
"downloadUrl": "http://qiniuyun.linruchang.work/23a0ef6824674374ab3e434c9d6046bf.epub",
"fileType": "epub",
"id": "068d928f5d14a160e6ab462421a62a91",
"isDel": 0,
"isViolation": 0,
"name": "尘埃落定",
"readingFeeling": "只为分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "Jon Bentley",
"country": "美国",
"createTime": "2021-01-20 23:15:49",
"downloadUrl": "http://qiniuyun.linruchang.work/6f8a0feab9084f97ada4ff3cbe44c25a.pdf",
"fileType": "pdf",
"id": "075054d08d23a27a772d8090f49131be",
"isDel": 0,
"isViolation": 0,
"name": "编程珠玑2- 中文版",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "莎拉·贝克韦尔",
"country": "英",
"createTime": "2021-01-24 01:37:38",
"downloadUrl": "http://qiniuyun.linruchang.work/4e60bfddf90e41f6aa52e8c8096ace22.pdf",
"fileType": "pdf",
"id": "082a5299564eac06c68b160c4f3f700d",
"isDel": 0,
"isViolation": 0,
"name": "存在主义咖啡馆:自由、存在和杏子鸡尾酒",
"readingFeeling": "只为分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "梦野久作",
"country": "日本",
"createTime": "2021-01-23 09:21:52",
"downloadUrl": "http://qiniuyun.linruchang.work/f0b38415cd7b4e9ea41c9d427dbff2cb.mobi",
"fileType": "mobi",
"id": "083c614e82c7bb7c7be3b1abe8bcaa69",
"isDel": 0,
"isViolation": 0,
"name": "脑髓地狱",
"readingFeeling": "只为上传",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "诺查丹玛斯",
"country": "法国",
"createTime": "2021-01-23 09:11:14",
"downloadUrl": "http://qiniuyun.linruchang.work/22b1b775ad0949be939616303af5b649.pdf",
"fileType": "pdf",
"id": "086d3141171658d51d7a9b8485d4de72",
"isDel": 0,
"isViolation": 0,
"name": "诸世纪(百诗集)",
"readingFeeling": "只为上传",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": " 斯科特·查康",
"country": "美",
"createTime": "2021-01-20 23:25:28",
"downloadUrl": "http://qiniuyun.linruchang.work/447686e70b924f27aada45478a922dda.pdf",
"fileType": "pdf",
"id": "08b756bca4e9644ba05cbf97fe03a5b0",
"isDel": 0,
"isViolation": 0,
"name": "Git官方文档中文版本",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "吴建斌",
"country": "中国",
"createTime": "2021-01-28 09:45:46",
"downloadUrl": "http://qiniuyun.linruchang.work/80117371e1b74cca8d1eceed1f7353cf.mobi",
"fileType": "mobi",
"id": "0a3c61744d170333158ce6b05066e6df",
"isDel": 0,
"isViolation": 0,
"name": "我在碧桂园的1000天",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "茂木健一郎",
"country": "日本",
"createTime": "2021-01-30 19:15:30",
"downloadUrl": "http://qiniuyun.linruchang.work/09726f56e3b64949b5bb7a3dc203a641.pdf",
"fileType": "pdf",
"id": "0ac3aeb73b56c54f53f3bdbdff8f19c1",
"isDel": 0,
"isViolation": 0,
"name": "逻辑思考的100个关键:系统建立逻辑思维,告别混乱人生",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "约翰·哈德森",
"country": "英国",
"createTime": "2021-01-30 19:15:46",
"downloadUrl": "http://qiniuyun.linruchang.work/36edde468ec44ad0a84840b67eb4cc0d.pdf",
"fileType": "pdf",
"id": "0df72ec7b3332bf70b43b98c673396c7",
"isDel": 0,
"isViolation": 0,
"name": "学会生存:如何成为一个生存能力很强的人",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "罗伯特·清崎",
"country": "美",
"createTime": "2021-01-20 22:32:40",
"downloadUrl": "http://qiniuyun.linruchang.work/26b40b3fd04446638ef234cd0cfce163.pdf",
"fileType": "pdf",
"id": "0e2a5fb0745e689688ef98f9e762d50d",
"isDel": 0,
"isViolation": 0,
"name": "富爸爸 房地产投资指南",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "王小波",
"country": "中国",
"createTime": "2021-01-20 22:19:15",
"downloadUrl": "http://qiniuyun.linruchang.work/f7244692cc0c4fe38c277518d003a039.mobi",
"fileType": "mobi",
"id": "0eaf2dc55d39e24c4a11a547df28045d",
"isDel": 0,
"isViolation": 0,
"name": "一只特立独行的猪",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "贾平凹",
"country": "中国",
"createTime": "2021-01-23 01:34:20",
"downloadUrl": "http://qiniuyun.linruchang.work/d7147580f67f489c9daef141fb7a00e7.mobi",
"fileType": "mobi",
"id": "104a543bf0db8e8b6e1bd501b78421a0",
"isDel": 0,
"isViolation": 0,
"name": "废都",
"readingFeeling": "只为分享\n",
"sharer": "嗯嗯**",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "萨缪尔·法努斯",
"country": "英",
"createTime": "2021-01-24 00:56:15",
"downloadUrl": "http://qiniuyun.linruchang.work/2521a8bd9f774a47964b92567a27edf8.epub",
"fileType": "epub",
"id": "10ed85bc799e2b1e3c86c0936cee08d8",
"isDel": 0,
"isViolation": 0,
"name": "墓志铭图书馆",
"readingFeeling": "只为分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "彩希子",
"country": "日",
"createTime": "2021-01-28 13:10:12",
"downloadUrl": "http://qiniuyun.linruchang.work/c8484f9ecc2c479d850a1fbb5a2efad5.pdf",
"fileType": "pdf",
"id": "10f247139be805a364a28b43158c9562",
"isDel": 0,
"isViolation": 0,
"name": "优雅,从姿势开始",
"readingFeeling": "分享\n",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "弗雷德里克·巴克曼",
"country": "瑞典",
"createTime": "2021-01-23 09:36:45",
"downloadUrl": "http://qiniuyun.linruchang.work/49746c05426946558526eba5ba9ab41f.mobi",
"fileType": "mobi",
"id": "10fbb56e7b5d62bada606a83abce43b2",
"isDel": 0,
"isViolation": 0,
"name": "时间的礼物",
"readingFeeling": "只为分享\n",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": " 约翰·埃里克森",
"country": "英国",
"createTime": "2021-01-31 13:26:13",
"downloadUrl": "http://qiniuyun.linruchang.work/e8c318e2a5d8413a920dcc15625e08d8.pdf",
"fileType": "pdf",
"id": "116e65aedafcac6ebb5e6434a1de47e9",
"isDel": 0,
"isViolation": 0,
"name": "通往柏林之路",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "罗伯特·清崎",
"country": "美",
"createTime": "2021-01-20 22:36:49",
"downloadUrl": "http://qiniuyun.linruchang.work/7fb1dd9ea1114b80b4904393eb929c05.pdf",
"fileType": "pdf",
"id": "12321d0f7ebbd1a30a782d2291940d01",
"isDel": 0,
"isViolation": 0,
"name": "富爸爸 财务自由之路",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "大卫·休谟",
"country": "英",
"createTime": "2021-01-25 09:36:55",
"downloadUrl": "http://qiniuyun.linruchang.work/e681a8166e14400c844b040ee3fc4656.pdf",
"fileType": "pdf",
"id": "1249db867157df409535a8bc9c9ba859",
"isDel": 0,
"isViolation": 0,
"name": "道德原则研究",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "德博拉·海登",
"country": "美国",
"createTime": "2021-01-31 21:53:01",
"downloadUrl": "http://qiniuyun.linruchang.work/36fd3ba3dbd24ebd87dc0dd786e3a4cb.pdf",
"fileType": "pdf",
"id": "13a747a481d0190b222c6aad99f3c05e",
"isDel": 0,
"isViolation": 0,
"name": "天才、狂人和梅毒",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "斯蒂芬·J.居耶内特",
"country": "英国",
"createTime": "2021-01-30 19:15:42",
"downloadUrl": "http://qiniuyun.linruchang.work/3760eac83f14448a8ccbe853fd28c0a4.pdf",
"fileType": "pdf",
"id": "141918ced3adbdbaa4b014f7f836487b",
"isDel": 0,
"isViolation": 0,
"name": "饥饿的大脑",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "查尔斯·卓别林",
"country": "英",
"createTime": "2021-01-24 01:33:26",
"downloadUrl": "http://qiniuyun.linruchang.work/a566f47008504ba5a2cf1aba7498cb92.mobi",
"fileType": "mobi",
"id": "1506cf3d549fc12a104a410e8be4bba8",
"isDel": 0,
"isViolation": 0,
"name": "卓别林自传",
"readingFeeling": "只为分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "钱钟书",
"country": "中国",
"createTime": "2021-01-28 09:45:06",
"downloadUrl": "http://qiniuyun.linruchang.work/eecaa6405a4a4d67af6336f4fcd06f1c.epub",
"fileType": "epub",
"id": "15c1f73c3fa82bf935dd0a708bdc2b22",
"isDel": 0,
"isViolation": 0,
"name": "围城(七十周年纪念版)",
"readingFeeling": "分享",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "孔繁任",
"country": "中国",
"createTime": "2021-01-23 01:03:27",
"downloadUrl": "http://qiniuyun.linruchang.work/87b1eb67172d4800bfd199d033ab321e.pdf",
"fileType": "pdf",
"id": "1610beccb39df1e1c3f346395b100715",
"isDel": 0,
"isViolation": 0,
"name": "故事化营销:让你的产品和品牌深入人心",
"readingFeeling": "帮网友找的书籍,随便上传到自己的博客,哈哈哈",
"sharer": "嗯嗯**",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "麦克伦尼",
"country": "美",
"createTime": "2021-01-20 22:39:33",
"downloadUrl": "http://qiniuyun.linruchang.work/72f3ebf7dc444360a6b2213a8acaa9fd.pdf",
"fileType": "pdf",
"id": "1699efe185d32f2474f697c117e06a02",
"isDel": 0,
"isViolation": 0,
"name": "简单的逻辑学",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
},
{
"author": "亨利·黑兹利特",
"country": "美",
"createTime": "2021-01-20 22:22:43",
"downloadUrl": "http://qiniuyun.linruchang.work/582a5579c6634b218a1512ad9bf92dc5.pdf",
"fileType": "pdf",
"id": "16ca9cf7c06a0bf49e1f8ebe36c1ee1a",
"isDel": 0,
"isViolation": 0,
"name": "一课经济学",
"sharer": "热心网友",
"status": "0",
"updateTime": "2021-06-06 19:36:08"
}
])
更新文档Update
//整数保存
NumberInt(数字)
//递增操作
db.表名.update({筛选条件},{ $inc: { 属性名: 需要增加的值 } })
//示例
db.article_comment_user.update({
id: "125451481858b589b8793a26aa8c44a1"
}, {
$inc: {
is_like: 5
}
})
简单使用
语法
//赋值操作JSON
{
$set: {"属性名":"属性值"."日期属性名":new Date()}, //设置属性
$unset: {"属性名":"属性值随便填写", ............}, //删除属性
$currentDate: { 日期属性: true } //将日期属性的值设置成当前更新时间
}
//0 整条记录替换为另一个JSON == 除了mondodb的ID主键不变即_id的属性值
db.数组名(表名).replaceOne(查询条件JSON, 新记录JSON)
//示例
db.book.replaceOne({
_id:ObjectId("6207698a3b61ea1433ac8157")
}, {
mark:"db.book.replcaeOne替换的记录",
time: new Date()
})
//1. 更新一个
db.数组名(表名).update(查询条件JSON, 赋值操作JSON)
db.数组名(表名).updateOne(查询条件JSON, 赋值操作JSON)
//示例
db.book.updateOne({
"id": { $in : ["02b65ed26a1e0938865bd76b0790ac12","05a5bec81474ded3683f1a5c900ff350"] }
}, {
"$set": { "isDel": 1, "time" : new Date()},
"$currentDate": { "updateTime": true},
})
//2. 更新多个
db.数组名(表名).updateMany(查询条件JSON, 赋值操作JSON)
//示例
db.book.updateMany({
"id": { $in : ["02b65ed26a1e0938865bd76b0790ac12","05a5bec81474ded3683f1a5c900ff350"] }
}, {
"$set": { "isDel": 2},
"$currentDate": { "updateTime": true},
})
整条记录替换
执行替换前的结果
执行替换后的结果
单条更新
多条更新
属性值是数组的操作
查询文档Read
更多的筛选条件学习
分类
符号 | 含义 |
---|---|
$eq | = |
$lt | < |
$lte | <= |
$gt | > |
$gte | >= |
$ne | != |
$in | 包含的值,跟SQL差不多一样的意思 |
$nin | 不包含的值,跟SQL差不多一样的意思 |
$or | 或条件 |
$and | 与条件 |
$type | key值的数据类型进行筛选 |
$not | 否定 |
$not | 否定 |
null | 空值筛选,如果仅选含有key的null则需要配合 $exists使用 |
$exists=true | 此元素必须含有属性名 |
$all | 某属性的值(数组),必须含有这些值,才能被筛选出来 |
$elemMatch | 用于属性值的数组元素,含有至少一个元素必须符合里面的所有条件 |
官网地址
find
语法
//1. 查询全部
db.数组名(表名).find();
//示例
db.book.find();
//1. 查询到的记录数
db.数组名(表名).find().count();
db.数组名(表名).find().length();
//示例
db.book.find().count();
//2. 等值and条件查
db.数组名(表名).find(正常JSON);
//示例
db.book.find({
country: "美国",
isDel: 0
})
//3. in条件 $in $nin
db.数组名(表名).find({
属性名: { $in: [多个属性值] }
});
//示例
db.book.find({
country: { $in: ["美国","日本"]},
isDel: 0
})
//比较运算符 $lt小于、$lte小于等于、$gt大于、$gte大于等于、$ne不等于
db.数组名(表名).find({
属性名: { $lt: [多个属性值] }
});
//示例
db.book.find({
createTime: { $gt: "2021-01-24 01:37:38"},
fileType: "pdf"
})
//or条件
db.数组名(表名).find({
$or: [{条件1},{条件2}]
});
//示例
db.book.find({
"$or": [
{
"createTime": {
"$gt": "2021-01-24 01:37:38"
},
"fileType": "pdf"
},
{
"country": "日"
}
]
})
//示例2
db.book.find({
"$or": [
{
"createTime": {
"$gt": "2021-01-24 01:37:38"
},
"fileType": "pdf"
},
{
"country": "日"
}
],
"readingFeeling": "分享"
})
查询全部
记录数
等值and条件查
in条件
比较运算符条件
or条件
findOne - 可获取整条记录以及列值 - Bean对象
db.数组名(表名).findOne(正常条件JSON);
//示例
db.book.findOne({country:"中国"})
db.数组名(表名).findOne(正常条件JSON).记录属性名;
//示例
db.book.findOne({country:"中国"}).name
分页 - (skip、limit)
skip跳过前面多少条数据
limit查询结果需要几天数据
//公式
skip((第N页-1)*每页显示条数).limit(每页显示条数)
全部数据
分页后的数据
多表关系查询 – 类似js语法
db.article.find();
db.article_user.find();
var article_id = db.article_user.findOne({id:"1f3c80b37013bca9b5902b93ac4d17eb"}).article_id;
db.article.find({id:article_id});
article表
article_user表
排序 - sort(1升序 -1降序)
//属性名1升序,如果遇到属性1一样的值,则按属性2降序排列
db.数组名(表名).find().sort({属性名:1, 属性名:-1})
//示例
db.sys_log.find().sort({
info: -1, execution_time: 1
});
仅显示需要的字段
//1需要显示,其他或者0默认不显示
db.数组名(表名).find({},{属性名:1})
//示例
db.sys_log
.find({},{info:1, execution_time:1})
.sort({execution_time:-1});
正则查询 - js的正则
db.article_tag.find();
// 含有【java】字眼
db.article_tag.find({tag_name: /java/});
// 以【java】结尾的
db.article_tag.find({tag_name: /java$/});
// 以【java】开头的
db.article_tag.find({tag_name: /^java/});
实现像Java的Iterable遍历、像容器的forEach方法
三个遍历都是一样的
var elemsIterable = db.test.find();
while(elemsIterable.hasNext()) {
var elem = elemsIterable.next();
print(elem,'=========',elem._id)
}
var elemsIterable = db.test.find();
elemsIterable.forEach(function(elem) {
print(elem,'=========',elem._id)
})
var elemsIterable = db.test.find();
elemsIterable.forEach(elem => {
print(elem,'=========',elem._id)
})
特殊字符 - DQL
$type - 键值的类型
类型 | 数字(查询使用的值) | 备注 | 别名(查询使用的值) |
---|---|---|---|
Double | 1 | double | |
String | 2 | string | |
Object | 3 | object | |
Array | 4 | array | |
Binary data | 5 | binData | |
Undefined | 6 | 已废弃。 | undefined |
ObjectId | 7 | objectId | |
Boolean | 8 | bool | |
Date | 9 | date | |
Null | 10 | null | |
Regular Expression | 11 | regex | |
JavaScript | 13 | javascript | |
Symbol | 14 | symbol | |
JavaScript (with scope) | 15 | javascriptWithScope | |
32-bit integer | 16 | int | |
Timestamp | 17 | timestamp | |
64-bit integer | 18 | long | |
Min key | 255 | Query with -1. | minKey |
Max key | 127 | maxKey |
//原始数据
db.test.insert([{
"books": [
"三国演义",
"红楼梦",
"水浒传"
],
id: "fdsfdsfdsfsd"
}, {
"books": [
"三国演义222",
"红楼梦222",
"水浒传2222",
"活着"
],
id: "fdsfdsfdsfsd423fsdf"
}, {
"books": [
"f删除VS地方",
"认为",
"水浒辅导费传2222",
"一天VN"
],
id: "543scvcxv"
},{
"books": 5,
id: "gdfgfd34534"
}])
//根据字段值进行筛选
db.test.find({books: {$type : 4}});
db.test.find({books: {$type : 'array'}});
db.test.find({books: {$type : 'double'}});
db.test.find({books: {$type : 1}});
$exists - 元素必须含有属性名筛选
db.test.find();
// 此元素的hobby属性值是没有值的记录
db.test.find({
hobby: { $eq: null}
})
// 此元素必须含有键hobby,且值是没有额记录
db.test.find({
hobby: { $eq: null, $exists:true}
})
$all - 用于属性值的数组的筛选 - 数组必须存有某几个元素
db.test.find();
//等值查询 == 某行元素有什么,查询的也必须有什么
db.test.find({books: [
"红楼梦",
"水浒传"
]});
db.test.find({books: [
"三国演义",
"红楼梦",
"水浒传"
]});
// 数组中存在元素【水浒传】的行记录
db.test.find({books: "水浒传"});
// 数组中必须存在元素【水浒传】跟 【红楼梦】行记录
//下面两句是等价的
db.test.find({ $and: [{books: "水浒传"}, {books: "红楼梦"}]});
db.test.find({books: {$all: ["水浒传","红楼梦"]}});
表全部数据
$elemMatch - 用于属性值的数组元素,含有至少一个元素必须符合里面的所有条件
db.test.find();
//存有元素 小于1
db.test.find({nums:{$elemMatch:{$lt:1}}})
//存有元素 大于5且小于20
db.test.find({nums:{$elemMatch:{$lt:20, $gt: 5}}})
聚合管道 - 跟Linux的管道|差不多
数据筛选阶段
数据运算阶段 - 运算符
简单使用 = 表的列使用"$列名" == 过滤,字符拼接
db.test.find();
//id属性值存有数字的行记录
db.test.find({
id: /\d+/
});
//先筛选 name不为空且books是数组的行记录,在进一步筛选id含有数字的行记录,最后在进行映射结果
db.test.aggregate([
{
$match:{
name : { $ne : null },
books: {$type: 'array'}
}
},
{
$match:{
id: /\d+/
}
},
{
$project:{
"姓名": "$name",
"书籍数组长度": {$size: "$books"},
"书籍数组长度是否大于3": { $gt: [{$size: "$books"}, 3] },
"姓名拼接id": {$concat : ["$name", "$id"]},
"姓名拼接_id": {$concat : ["$name", {$toString:"$_id"}]}
}
}
])
简单使用 = 表的列使用"$列名" == 分组,排序
db.test.find();
//根据country进行分组,然后算各组C的平均数
db.test.aggregate([
{
$group: {
_id: "$country",
avgC: {
$avg: "$c"
}
}
},
{
$sort: { avgC : -1}
}
])
自定义JS函数分组使用$accumulator
数据
db.restaurants.insertMany([
{ "_id" : 1, "name" : "Food Fury", "city" : "Bettles", "cuisine" : "American" },
{ "_id" : 2, "name" : "Meal Macro", "city" : "Bettles", "cuisine" : "Chinese" },
{ "_id" : 3, "name" : "Big Crisp", "city" : "Bettles", "cuisine" : "Latin" },
{ "_id" : 4, "name" : "The Wrap", "city" : "Onida", "cuisine" : "American" },
{ "_id" : 5, "name" : "Spice Attack", "city" : "Onida", "cuisine" : "Latin" },
{ "_id" : 6, "name" : "Soup City", "city" : "Onida", "cuisine" : "Chinese" },
{ "_id" : 7, "name" : "Crave", "city" : "Pyote", "cuisine" : "American" },
{ "_id" : 8, "name" : "The Gala", "city" : "Pyote", "cuisine" : "Chinese" }
])
db.restaurants.aggregate([
{
$group :
{
_id : { city: "$city" },
restaurants:
{
$accumulator:
{
init: function(city, userProfileCity) {
return {
max: city === userProfileCity ? 3 : 1,
restaurants: []
}
},
initArgs: ["$city","Onida"],
accumulate: function(state, restaurantName) {
if (state.restaurants.length < state.max) {
state.restaurants.push(restaurantName);
}
return state;
},
accumulateArgs: ["$name"],
merge: function(state1, state2) {
return {
max: state1.max,
restaurants: state1.restaurants.concat(state2.restaurants).slice(0, state1.max)
}
},
finalize: function(state) {
return state.restaurants
},
lang: "js"
}
}
}
}
])
将上面的案例直接转换成真正的JS代码 == 更加的易懂
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
<script>
var objs = [
{ _id: 1, name: "Food Fury", city: "Bettles", cuisine: "American" },
{ _id: 2, name: "Meal Macro", city: "Bettles", cuisine: "Chinese" },
{ _id: 3, name: "Big Crisp", city: "Bettles", cuisine: "Latin" },
{ _id: 4, name: "The Wrap", city: "Onida", cuisine: "American" },
{ _id: 5, name: "Spice Attack", city: "Onida", cuisine: "Latin" },
{ _id: 6, name: "Soup City", city: "Onida", cuisine: "Chinese" },
{ _id: 7, name: "Crave", city: "Pyote", cuisine: "American" },
{ _id: 8, name: "The Gala", city: "Pyote", cuisine: "Chinese" },
];
//分组 == 按city的值
var groups = {};
objs.forEach((item, index) => {
if (!groups[item.city]) {
groups[item.city] = [];
}
groups[item.city].push(item);
});
console.log("=============分组开始==============")
console.log(groups);
console.log("=============分组结束==============")
//==========================MongoDB的聚合【直接粘贴复制的】==============================================
function init(city, userProfileCity) {
let state = {
max: city === userProfileCity ? 3 : 1,
restaurants: [],
};
return state;
}
function accumulate(state, restaurantName) {
if (state.restaurants.length < state.max) {
state.restaurants.push(restaurantName);
}
return state;
}
function merge(state1, state2) {
return {
max: state1.max,
restaurants: state1.restaurants
.concat(state2.restaurants)
.slice(0, state1.max),
};
}
function finalize(state) {
return state.restaurants
}
//========================================================================
var initGroups = {};
for( let groupName in groups) {
var groupElems = groups[groupName];
initGroups[groupName] = JSON.parse(JSON.stringify(groupElems));
var initGroupElems = initGroups[groupName];
for(var index = 0 ; index < groupElems.length; index++) {
//等价于 initArgs: ["$city","Onida"]
let state = init(groupName, "Onida");
//等价于accumulateArgs: ["$name"]
initGroupElems[index] = accumulate(state, groupElems[index]["name"])
}
//等价于merge
var metgeResult = initGroupElems.reduce( merge );
//等价于finalize
initGroups[groupName] = finalize(metgeResult);
}
console.log("=============分组聚合后的结果==开始============")
console.log(initGroups);
console.log("=============分组聚合后的结果==结束============")
</script>
</html>
删除文档Delete
//删除一个
db.数组名(表名).deleteOne(正常条件JSON);
db.数组名(表名).remove(正常条件JSON,true);
db.数组名(表名).remove({}); //删此表
//删除多个
db.数组名(表名).deleteMany(正常条件JSON);
db.数组名(表名).remove(正常条件JSON);
删除前
删除操作
删除后