MongoDB的安装与CRUD操作

一、MongoDB简介
  MongoDB是NoSQL数据库类型的一种,由C++语言编写,旨在为WEB应用提供可扩展的高性能数据存储解决方案;MongoDB数据库是一个介于关系数据库和非关系数据库之间的一个产品,是非关系数据库中功能最为丰富的、最像关系数据库的文档数据库,它支持的数据结构类型非常松散,是类似于json的bson格式,因此可以存储比较复杂的数据类型。MongoDB最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引与数据库复制功能。

常用的NoSQL数据存储类型有:

数据类型 代表产品
列式存储 hbase
键值存储 redis
文档存储 mongodb
图式存储 neo4j

MongoDB的特点有:
  1)高性能、易部署、存储方便
  2)面向集合存储,易存储对象类型的数据
  3)模式自由
  4)支持动态查询
  5)支持完全索引,包含内部对象
  6)支持复制和故障恢复
  7)使用高效的二进制数据存储,包括大型对象(如视频等)
  8)自动处理碎片,以支持云计算层次的扩展性
  9)文件存储格式为BSON(JSON格式的一种扩展)
  10)可以通过网络访问

二、安装部署MongoDB
1)配置yum源指向mongodb官网

[root@jyy ~]# cd  /etc/yum.repos.d/
[root@jyy yum.repos.d]# cat mongodb.repo 
[mongodb-org-3.4]  
name=MongoDB Repository  
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/  
gpgcheck=1  
enabled=1  
gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc

[root@jyy yum.repos.d]# 
[root@jyy yum.repos.d]# yum repolist all 
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                             | 5.2 kB  00:00:00     
 * epel: mirror01.idc.hinet.net
base                                                                             | 3.6 kB  00:00:00     
epel                                                                             | 5.3 kB  00:00:00     
file:///mnt/cdrom/repodata/repomd.xml: [Errno 14] curl#37 - "Couldn't open file /mnt/cdrom/repodata/repomd.xml"
Trying other mirror.
mongodb-org-3.4                                                                  | 2.5 kB  00:00:00     
(1/3): epel/x86_64/updateinfo                                                    | 984 kB  00:00:01     
(2/3): epel/x86_64/primary_db                                                    | 6.7 MB  00:00:01     
(3/3): mongodb-org-3.4/7/primary_db                                              |  89 kB  00:00:07     
repo id                       repo name                                                  status
base/x86_64                   CentOS-7 - Base - mirrors.aliyun.com                       enabled: 10,019
epel/x86_64                   Extra Packages for Enterprise Linux 7 - x86_64             enabled: 13,283
!jyy                          jyy                                                        enabled:  3,971
mongodb-org-3.4/7             MongoDB Repository                                         enabled:    110
repolist: 27,383

2)安装mongodb数据库并启动服务

[root@jyy yum.repos.d]# yum install   mongodb-org   
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * epel: mirror01.idc.hinet.net
Resolving Dependencies
--> Running transaction check
---> Package mongodb-org.x86_64 0:3.4.21-1.el7 will be installed
--> Processing Dependency: mongodb-org-tools = 3.4.21 for package: mongodb-org-3.4.21-1.el7.x86_64
--> Processing Dependency: mongodb-org-shell = 3.4.21 for package: mongodb-org-3.4.21-1.el7.x86_64
--> Processing Dependency: mongodb-org-server = 3.4.21 for package: mongodb-org-3.4.21-1.el7.x86_64
--> Processing Dependency: mongodb-org-mongos = 3.4.21 for package: mongodb-org-3.4.21-1.el7.x86_64
--> Running transaction check
---> Package mongodb-org-mongos.x86_64 0:3.4.21-1.el7 will be installed
---> Package mongodb-org-server.x86_64 0:3.4.21-1.el7 will be installed
---> Package mongodb-org-shell.x86_64 0:3.4.21-1.el7 will be installed
---> Package mongodb-org-tools.x86_64 0:3.4.21-1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

========================================================================================================
 Package                      Arch             Version                  Repository                 Size
========================================================================================================
Installing:
 mongodb-org                  x86_64           3.4.21-1.el7             mongodb-org-3.4           5.8 k
Installing for dependencies:
 mongodb-org-mongos           x86_64           3.4.21-1.el7             mongodb-org-3.4            12 M
 mongodb-org-server           x86_64           3.4.21-1.el7             mongodb-org-3.4            20 M
 mongodb-org-shell            x86_64           3.4.21-1.el7             mongodb-org-3.4            11 M
 mongodb-org-tools            x86_64           3.4.21-1.el7             mongodb-org-3.4            69 M

Transaction Summary
========================================================================================================
Install  1 Package (+4 Dependent packages)

Total size: 112 M
Installed size: 286 M
Is this ok [y/d/N]: y
Downloading packages:
warning: /var/cache/yum/x86_64/7/mongodb-org-3.4/packages/mongodb-org-mongos-3.4.21-1.el7.x86_64.rpm: Header V3 RSA/SHA1 Signature, key ID a15703c6: NOKEY
Retrieving key from https://www.mongodb.org/static/pgp/server-3.4.asc
Importing GPG key 0xA15703C6:
 Userid     : "MongoDB 3.4 Release Signing Key <[email protected]>"
 Fingerprint: 0c49 f373 0359 a145 1858 5931 bc71 1f9b a157 03c6
 From       : https://www.mongodb.org/static/pgp/server-3.4.asc
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : mongodb-org-server-3.4.21-1.el7.x86_64                                               1/5 
Created symlink from /etc/systemd/system/multi-user.target.wants/mongod.service to /usr/lib/systemd/system/mongod.service.
  Installing : mongodb-org-shell-3.4.21-1.el7.x86_64                                                2/5 
  Installing : mongodb-org-tools-3.4.21-1.el7.x86_64                                                3/5 
  Installing : mongodb-org-mongos-3.4.21-1.el7.x86_64                                               4/5 
  Installing : mongodb-org-3.4.21-1.el7.x86_64                                                      5/5 
  Verifying  : mongodb-org-mongos-3.4.21-1.el7.x86_64                                               1/5 
  Verifying  : mongodb-org-tools-3.4.21-1.el7.x86_64                                                2/5 
  Verifying  : mongodb-org-shell-3.4.21-1.el7.x86_64                                                3/5 
  Verifying  : mongodb-org-3.4.21-1.el7.x86_64                                                      4/5 
  Verifying  : mongodb-org-server-3.4.21-1.el7.x86_64                                               5/5 

Installed:
  mongodb-org.x86_64 0:3.4.21-1.el7                                                                     

Dependency Installed:
  mongodb-org-mongos.x86_64 0:3.4.21-1.el7           mongodb-org-server.x86_64 0:3.4.21-1.el7          
  mongodb-org-shell.x86_64 0:3.4.21-1.el7            mongodb-org-tools.x86_64 0:3.4.21-1.el7           

Complete!
[root@jyy yum.repos.d]# 





[root@jyy yum.repos.d]# systemctl start    mongod  ;  systemctl enable  mongod 
[root@jyy yum.repos.d]# ss -tunlp | grep    mongod 
tcp    LISTEN     0      128    127.0.0.1:27017                 *:*                   users:(("mongod",pid=1507,fd=7))
		##数据库已然安装成功,端口号为27017


服务器程序为:mongod
客户端程序为:mongo   --host   --port

三、MongoDB的CRUD常用操作:
  1)增加:mongodb的数据库是由数据库(database)、集合(collection)、文档(document)三个层次组成;一个数据库中可以有多个集合、一个集合中可以存在多个文档。

[root@jyy ~]# mongo --host 127.0.0.1 --port 27017   //连接数据库
MongoDB shell version v3.4.21
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 3.4.21
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
	http://docs.mongodb.org/
Questions? Try the support group
	http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] 
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] 
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] 
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] 
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-07-06T15:45:32.567+0800 I CONTROL  [initandlisten] 
>			//出现shell提示符就是连接成功!
> 
> 
> show databases;     //查询所有的数据库;
admin  0.000GB
local  0.000GB
> 
> use test;     //进入数据库,不存在时mongo会自动创建;
switched to db test
> 
> db.student.insert({name:"aaa",age:6,gender:"n"});    //往student集合中插入一条数据;
													 集合不存在时mongo也会自动创建
WriteResult({ "nInserted" : 1 })
> db.collections;		//查询所有的集合;
test.collections
> 
> db.student.insert([{name:"bbb",age:7,gender:"n"},{name:"ccc",age:8,gender:"n"}]);
	//一次性插入多条记录操作;		
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
> 

2)查询操作:

> db.student.find();     //查询所有文档数据;
{ "_id" : ObjectId("5d20542454ddc69eb4bf473c"), "name" : "aaa", "age" : 6, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473d"), "name" : "bbb", "age" : 7, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473e"), "name" : "ccc", "age" : 8, "gender" : "n" }
> 
> db.student.find().limit(2);     //限制输出数据数量;
{ "_id" : ObjectId("5d20542454ddc69eb4bf473c"), "name" : "aaa", "age" : 6, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473d"), "name" : "bbb", "age" : 7, "gender" : "n" }
> 
> 
> db.student.find().count();    //统计文档数据的数量
3
> 
> 
> 
> db.student.findOne();     //只查询一条数据记录;
{
	"_id" : ObjectId("5d20542454ddc69eb4bf473c"),
	"name" : "aaa",
	"age" : 6,
	"gender" : "n"
}
> 
> 
> db.student.find({name:"ccc"});    //只查询name为"ccc"的文档数据;
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473e"), "name" : "ccc", "age" : 8, "gender" : "n" }
> 

find较为复杂的查询操作:
	比较操作:$gt,{field:{$gt:value}}、$get、$lt、$lte、$ne、$in、$nin
	逻辑操作:$or、$and,$not、{$or:[{},{}]}
	存在性判断:$exists
	值类型判断:$type

3)更新操作:
  更新一个文档数据时需要先定位找到此文档数据,然后要使用$set关键字进行修改操作,$unset用于删除指定的字段数据;

> db.student.update({name:"bbb"},{$set:{age:1000}});      //修改bbb的age大小为1000
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.student.find({name:"bbb"});    //验证是否修改成功
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473d"), "name" : "bbb", "age" : 1000, "gender" : "n" }
> 
> db.student.update({name:"ccc"},{$unset:{age:8}});    //删除name为"ccc"的age字段;
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> 
> db.student.find({name:"ccc"});    //验证是否删除成功;
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473e"), "name" : "ccc", "gender" : "n" }
> 

4)删除操作:

> 
> db.student.find({});
{ "_id" : ObjectId("5d20542454ddc69eb4bf473c"), "name" : "aaa", "age" : 6, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473d"), "name" : "bbb", "age" : 1000, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473e"), "name" : "ccc", "gender" : "n" }
> 
> db.student.remove({name:"ccc"});    //删除name为"ccc"的文档数据记录;
WriteResult({ "nRemoved" : 1 })
> 
> 
> db.student.find({});        //验证是否删除成功;
{ "_id" : ObjectId("5d20542454ddc69eb4bf473c"), "name" : "aaa", "age" : 6, "gender" : "n" }
{ "_id" : ObjectId("5d2054f154ddc69eb4bf473d"), "name" : "bbb", "age" : 1000, "gender" : "n" }
> 
> 
> show collections;
student
> 
> db.student.drop();    //删除student集合;
true
> 
> show collections;
> 
> db.dropDatabase();    //删除当前库;
{ "dropped" : "test", "ok" : 1 }
> 
> 
> show  databases;
admin  0.000GB
local  0.000GB
> 
> 
> use local;
switched to db local
> 
> db.stats();    //查看当前所数据库的状态信息;
{
	"db" : "local",
	"collections" : 1,
	"views" : 0,
	"objects" : 1,
	"avgObjSize" : 1690,
	"dataSize" : 1690,
	"storageSize" : 16384,
	"numExtents" : 0,
	"indexes" : 1,
	"indexSize" : 16384,
	"ok" : 1
}
> 

发布了83 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Micky_Yang/article/details/94861030