本文目录
1.MongoDB介绍
MongoDB 是一个跨平台、面向文档的数据库,可提供高性能、高可用性和易于扩展的特性。 MongoDB 是NoSQL(Not Only SQL) 数据库的一种。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库中功能最丰富、 最像关系数据库的。在高负载的情况下,通过添加更多的节点,可以保证服务器性能。
NoSQL=Not Only SQL,支持类似SQL的功能, 与Relational Database相辅相成。其性能较高, 不使用SQL意味着没有结构化的存储要求(SQL为结构化的查询语句),没有约束之后架构更加灵 活。 NoSQL数据库四大家族, 列存储 Hbase,键值(Key-Value)存储 Redis,图像存储 Neo4j,文档存储 MongoDB。
1.1 MongoDB 和关系型数据库对比
下表是 关系型数据库(RDBMS )术语与 MongoDB 对比
RDBMS | MongoDB |
---|---|
Database(数据库) | Database(数据库) |
Table(表) | Collection(集合) |
Tuple/Row(行) | Document(文档) |
column(列) | Field(字段) |
Table Join(主外键关联) | Embedded Documents (嵌套文档) |
Primary Key(指定1至N个列做主键) | Primary Key (Default key _id provided by MongoDB itself) |
1.2 MongoDB 结构
-
Database(数据库)
数据库是集合的物理容器。每个数据库在文件系统上都有自己的一组文件。单个 MongoDB 服务器通常具有多个数据库。
-
Collection(集合)
集合是一组 MongoDB 文档。 它相当于一个 RDBMS 表。 集合存在于单个数据库中。 集合中的文档可以有不同的字段。 通常,集合中的所有文档都具有相似或相关的目的。
-
Document(文档)
文档是一组键值对。 文档具有动态架构。 动态模式意味着同一集合中的文档不需要具有相同的字段集或结构,并且集合文档中的公共字段可能包含不同类型的数据。
MongoDB 支持多种数据类型。其中一些是 -
- String − This is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid.
- Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
- Boolean − This type is used to store a boolean (true/ false) value.
- Double − This type is used to store floating point values.
- Min/ Max keys − This type is used to compare a value against the lowest and highest BSON elements.
- Arrays − This type is used to store arrays or list or multiple values into one key.
- Timestamp − ctimestamp. This can be handy for recording when a document has been modified or added.
- Object − This datatype is used for embedded documents.
- Null − This type is used to store a Null value.
- Symbol − This datatype is used identically to a string; however, it’s generally reserved for languages that use a specific symbol type.
- Date − This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
- Object ID − This datatype is used to store the document’s ID.
- Binary data − This datatype is used to store binary data.
- Code − This datatype is used to store JavaScript code into the document.
- Regular expression − This datatype is used to store regular expression.
2.在Linux上安装MongoDB
-
下载社区版MongoDB
下载地址:https://www.mongodb.com/try/download/community
-
将压缩包解压
tar -zxvf mongodb-linux-x86_64-rhel70-4.2.17.tgz
-
添加配置文件
进入到mongodb目录,添加mongo.conf 文件
#存储目录 dbpath=/data/mongo/ #端口号 port=27017 # 允许远程访问的IP。 0.0.0.0表示不做限制 bind_ip=0.0.0.0 # 后台进程的方式启动 fork=true # 日志目录 logpath = /data/mongo/MongoDB.log # 日志是否追加 logappend = true # 是否开启用户密码登录 auth=false
-
启动
进入到mongodb目录,执行命令
[root@localhost mongodb-4.2.17]# ./bin/mongod -f mongo.conf
查看是否启动成功
[root@localhost mongodb-4.2.17]# ps -ef | grep mongo
-
启动mongo shell
首先进入到mongodb目录。
启动命令:
./bin/mongo --host=主机IP --port=端口
如果不指定host和port参数,默认链接本机端口号为27017的Mongodb服务。
3.MongoDB 图形化链接工具
3.1 MongoDB Compass Community
MongoDB Compass Community由MongoDB开发人员开发,这意味着更高的可靠性和兼容性。它为 MongoDB提供GUI mongodb工具,以探索数据库交互,具有完整的CRUD功能并提供可视方式。借助 内置模式可视化,用户可以分析文档并显示丰富的结构。为了监控服务器的负载,它提供了数据库操作 的实时统计信息。就像MongoDB一样,Compass也有两个版本,一个是Enterprise(付费),社区可 以免费使用。适用于Linux,Mac或Windows。
下载地址:https://www.mongodb.com/try/download/compass
3.2 NoSQLBooster
NoSQLBooster是MongoDB CLI界面中非常流行的GUI工具。它正式名称为MongoBooster。 NoSQLBooster是一个跨平台,它带有一堆mongodb工具来管理数据库和监控服务器。这个Mongodb 工具包括服务器监控工具,Visual Explain Plan,查询构建器,SQL查询,ES2017语法支持等等…它 有免费,个人和商业版本,当然,免费版本有一些功能限制。NoSQLBooster也可用于Windows, MacOS和Linux。
下载地址:https://nosqlbooster.com/downloads
4.MongoDB基本操作
# 查看数据库
show dbs;
# 切换数据库
use admin;
# 创建集合
db.createCollection("集合名")
#查看集合
show collections;
# 删除集合
db.集合名.drop();
4.1.MongoDB集合数据CRUD
① 数据添加
-
插入单条数据
语法:
db.集合名.insert(文档)
示例:db.test.insert({name:"张三",sex:"男",age:22,address:"china beijing"})
-
插入多条数据
语法:
db.集合名.insert([文档,文档])
示例:
db.test.insert([{name:"李四",sex:"男",age:22,address:"china beijing"},
{name:"小兰",sex:"女",age:22,address:"china beijing"}])
② 数据查询
-
语法:
db.集合名.find([条件])
.pretty() -
查询操作符
关系型数据库(RDBMS )Where 子句在 MongoDB 中的等价物
操作符 语法 示例 RDBMS中的条件 = {:{$eg;}} db.mycol.find({“by”:“tutorials point”}).pretty() where by = ‘tutorials point’ < {:{$lt:}} db.mycol.find({“likes”:{$lt:50}}).pretty() where likes < 50 <= {:{$lte:}} db.mycol.find({“likes”:{$lte:50}}).pretty() where likes <= 50 > {:{$gt:}} db.mycol.find({“likes”:{$gt:50}}).pretty() where likes > 50 >= {:{$gte:}} db.mycol.find({“likes”:{$gte:50}}).pretty() where likes >= 50 != {:{$ne:}} db.mycol.find({“likes”:{$ne:50}}).pretty() where likes != 50 in {:{$in:[, ,……]}} db.mycol.find({“name”:{$in:[“Raj”, “Ram”, “Raghu”]}}).pretty() Where name matches any of the value in :[“Raj”, “Ram”, “Raghu”] not in {:{$nin:}} db.mycol.find({“name”:{$nin:[“Ramu”, “Raghav”]}}).pretty() Where name values is not in the array :[“Ramu”, “Raghav”] or, doesn’t exist at all -
示例1:查询年龄等于20的人员:
db.test.find({age:22}) .sort({_id:-1}) .limit(100).pretty()
-
示例2:查询年龄小于20的人员
db.test.find({"age":{$lt: 30}}) .sort({_id:-1}) .limit(100).pretty()
-
-
逻辑条件查
-
AND
语法:
db.集合.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
示例,查询名字为张三并且年龄为20岁的人员:db.test.find({$and: [{name:"张三"},{age:20}]}) .sort({_id:-1}) .limit(100).pretty()
-
OR
语法:
db.集合名.find({$or:[{key1:value1}, {key2:value2}]}).pretty()
示例,查询名字为张三或者年龄为20岁的人员:
db.test.find({$or: [{name:"张三"},{age:20}]}) .sort({_id:-1}) .limit(100).pretty()
-
-
分页查询
语法:db.集合名.find({条件}).sort({排序字段:排序方式})).skip(跳过的行数).limit(一页显示多少数据)
示例:
db.test.find({$or: [{name:"张三"},{age:20}]}) .sort({_id:-1}) .skip(0) .limit(100).pretty()
③ 更新
-
语法
db.集合名.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document> } )
-
参数说明:
-
query : update的查询条件,类似sql update查询内where后面的。
-
update : 可选值如下:
$set :设置字段值
$unset :删除指定字段$inc:对修改的值进行自增
-
upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认 是false,不插入。
-
multi : 可选,MongoDB 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查 出来多条记录全部更新。
-
-
示例:
# 把名字叫张三的年龄改为25 db.test.update({name:'张三'}, {$set:{age:25}}, { multi: true, upsert: false} )
④ 删除
-
语法
db.collection.remove( <query>, { justOne: <boolean>, writeConcern: <document> }) 参数说明: query :(可选)删除的文档的条件。 justOne : (可选)如果设为 true 或 1,则只删除一个文档,如果不设置该参数,或使用默认值false,则删除所有匹配条件的文档。 writeConcern :(可选)用来指定mongod对写操作的回执行为。
-
示例
# 删除年龄为25的人员 db.test.remove({age:25}, {justOne: true})