MongoDB数据库(一):基本操作

1.NoSQL的概念

"NoSQL"一词最早于1998年被用于一个轻量级的关系数据库的名字
随着web2.0的快速发展,NoSQL概念在2009年被提了出来
NoSQL最常见的解释是"non-relational","Not Only SQL"也被很多人接受,指的是非关系型数据库

2.关系型数据库和非关系型的区别

关系型数据库很强大,但是并不能很好的应付所有的场景.关系型数据库的扩展性差,大数据下IO压力大,表结构更改困难

非关系型数据库易扩展,大数据量高性能,灵活的数据模型,高可用

3.MongoDB数据库的优势

  • 易扩展:去掉关系型数据库的关系型特性,数据之间无关系,非常容易扩展
  • 大数据量,高性能:得益于无关系性,数据库的结构简单,有非常高的读写性能,尤其是在大数据量下,同样表现优秀
  • 灵活的数据模型:无需事先为要存储的数据建立字段,随时可以存储自定义的数据格式

4.安装及启动MongoDB数据库

4.1 安装EPEL源

[root@localhost ~]# yum list | grep epel
epel-release.noarch                        7-11                        @extras  
htop.x86_64                                2.2.0-3.el7                 @epel    
libdb4.x86_64                              4.8.30-13.el7               @epel    
libdb4-devel.x86_64                        4.8.30-13.el7               @epel    
python2-pip.noarch                         8.1.2-7.el7                 @epel    
[root@localhost ~]# yum install -y epel-release                 # MongoDB包含在EPEL源里面,所以在安装MongoDB必须先安装EPEL源
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be reinstalled
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================================
    Package                      Arch                   Version                 Repository              Size
==========================================================================================================
Reinstalling:
    epel-release                 noarch                 7-11                    extras                  15 k

Transaction Summary
==========================================================================================================
Reinstall  1 Package

Total download size: 15 k
Installed size: 24 k
Downloading packages:
epel-release-7-11.noarch.rpm                                                       |  15 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
    Installing : epel-release-7-11.noarch                                                               1/1 
    Verifying  : epel-release-7-11.noarch                                                               1/1 

Installed:
    epel-release.noarch 0:7-11                                                                              

Complete!
[root@localhost ~]# ls /etc/yum.repos.d/
CentOS-Base.repo  epel.repo  epel-testing.repo

4.2 安装MongoDB数据库

[root@localhost ~]# yum clean all               # 清除yum缓存
Loaded plugins: fastestmirror
Cleaning repos: base code epel extras updates
Cleaning up everything
Maybe you want: rm -rf /var/cache/yum, to also free up space taken by orphaned data from disabled or removed repos
Cleaning up list of fastest mirrors
[root@localhost ~]# yum makecache               # 重新生成yum缓存文件
Loaded plugins: fastestmirror
Determining fastest mirrors
epel/x86_64/metalink                                                               | 7.3 kB  00:00:00     
    * epel: mirrors.aliyun.com
base                                                                               | 3.6 kB  00:00:00     
code                                                                               | 2.9 kB  00:00:00     
epel                                                                               | 4.7 kB  00:00:00     
extras                                                                             | 3.4 kB  00:00:00     
updates                                                                            | 3.4 kB  00:00:00     
(1/21): base/7/x86_64/filelists_db                                                 | 7.1 MB  00:00:01     
(2/21): base/7/x86_64/primary_db                                                   | 6.0 MB  00:00:00     
(3/21): base/7/x86_64/other_db                                                     | 2.6 MB  00:00:00     
(4/21): code/primary_db                                                            |  40 kB  00:00:00     
(5/21): epel/x86_64/group_gz                                                       |  88 kB  00:00:00     
(6/21): code/filelists_db                                                          | 688 kB  00:00:01     
(7/21): epel/x86_64/updateinfo                                                     | 1.0 MB  00:00:00     
(8/21): epel/x86_64/prestodelta                                                    |  11 kB  00:00:00     
(9/21): code/other_db                                                              | 2.2 kB  00:00:00     
(10/21): epel/x86_64/primary_db                                                    | 6.6 MB  00:00:01     
(11/21): extras/7/x86_64/filelists_db                                              | 231 kB  00:00:00     
(12/21): extras/7/x86_64/prestodelta                                               |  47 kB  00:00:00     
(13/21): extras/7/x86_64/primary_db                                                | 180 kB  00:00:00     
(14/21): base/7/x86_64/group_gz                                                    | 166 kB  00:00:05     
(15/21): updates/7/x86_64/prestodelta                                              | 358 kB  00:00:00     
(16/21): updates/7/x86_64/filelists_db                                             | 2.2 MB  00:00:00     
(17/21): extras/7/x86_64/other_db                                                  | 118 kB  00:00:00     
(18/21): updates/7/x86_64/other_db                                                 | 351 kB  00:00:00     
(19/21): epel/x86_64/other_db                                                      | 3.2 MB  00:00:01     
(20/21): updates/7/x86_64/primary_db                                               | 2.5 MB  00:00:00     
(21/21): epel/x86_64/filelists_db                                                  |  11 MB  00:00:10     
Metadata Cache Created
[root@localhost ~]# yum install -y mongodb mongodb-server               # 安装MongoDB数据库
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
    * epel: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package mongodb.x86_64 0:2.6.12-6.el7 will be installed
--> Processing Dependency: v8 >= 3.14.5.10 for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libboost_filesystem-mt.so.1.53.0()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libboost_program_options-mt.so.1.53.0()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libpcap.so.1()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libstemmer.so.0()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libtcmalloc.so.4()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libv8.so.3()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
--> Processing Dependency: libyaml-cpp.so.0.5()(64bit) for package: mongodb-2.6.12-6.el7.x86_64
---> Package mongodb-server.x86_64 0:2.6.12-6.el7 will be installed
--> Running transaction check
---> Package boost-filesystem.x86_64 0:1.53.0-27.el7 will be installed
---> Package boost-program-options.x86_64 0:1.53.0-27.el7 will be installed
---> Package gperftools-libs.x86_64 0:2.6.1-1.el7 will be installed
---> Package libpcap.x86_64 14:1.5.3-11.el7 will be installed
---> Package libstemmer.x86_64 0:0-2.585svn.el7 will be installed
---> Package v8.x86_64 1:3.14.5.10-25.el7 will be installed
---> Package yaml-cpp.x86_64 1:0.5.1-1.el7.2 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================================
    Package                          Arch              Version                         Repository       Size
==========================================================================================================
Installing:
    mongodb                          x86_64            2.6.12-6.el7                    epel             43 M
    mongodb-server                   x86_64            2.6.12-6.el7                    epel            6.6 M
Installing for dependencies:
    boost-filesystem                 x86_64            1.53.0-27.el7                   base             68 k
    boost-program-options            x86_64            1.53.0-27.el7                   base            156 k
    gperftools-libs                  x86_64            2.6.1-1.el7                     base            272 k
    libpcap                          x86_64            14:1.5.3-11.el7                 base            138 k
    libstemmer                       x86_64            0-2.585svn.el7                  epel             67 k
    v8                               x86_64            1:3.14.5.10-25.el7              epel            3.0 M
    yaml-cpp                         x86_64            1:0.5.1-1.el7.2                 epel            176 k

Transaction Summary
==========================================================================================================
Install  2 Packages (+7 Dependent packages)

Total download size: 54 M
Installed size: 164 M
Downloading packages:
(1/9): boost-filesystem-1.53.0-27.el7.x86_64.rpm                                   |  68 kB  00:00:03     
(2/9): boost-program-options-1.53.0-27.el7.x86_64.rpm                              | 156 kB  00:00:05     
(3/9): libpcap-1.5.3-11.el7.x86_64.rpm                                             | 138 kB  00:00:00     
(4/9): gperftools-libs-2.6.1-1.el7.x86_64.rpm                                      | 272 kB  00:00:04     
(5/9): libstemmer-0-2.585svn.el7.x86_64.rpm                                        |  67 kB  00:00:03     
(6/9): mongodb-server-2.6.12-6.el7.x86_64.rpm                                      | 6.6 MB  00:00:01     
(7/9): v8-3.14.5.10-25.el7.x86_64.rpm                                              | 3.0 MB  00:00:01     
(8/9): yaml-cpp-0.5.1-1.el7.2.x86_64.rpm                                           | 176 kB  00:00:00     
(9/9): mongodb-2.6.12-6.el7.x86_64.rpm                                             |  43 MB  00:00:30     
----------------------------------------------------------------------------------------------------------
Total                                                                     1.5 MB/s |  54 MB  00:00:36     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
    Installing : boost-filesystem-1.53.0-27.el7.x86_64                                                  1/9 
    Installing : 1:yaml-cpp-0.5.1-1.el7.2.x86_64                                                        2/9 
    Installing : boost-program-options-1.53.0-27.el7.x86_64                                             3/9 
    Installing : gperftools-libs-2.6.1-1.el7.x86_64                                                     4/9 
    Installing : 1:v8-3.14.5.10-25.el7.x86_64                                                           5/9 
    Installing : libstemmer-0-2.585svn.el7.x86_64                                                       6/9 
    Installing : 14:libpcap-1.5.3-11.el7.x86_64                                                         7/9 
    Installing : mongodb-2.6.12-6.el7.x86_64                                                            8/9 
    Installing : mongodb-server-2.6.12-6.el7.x86_64                                                     9/9 
    Verifying  : mongodb-2.6.12-6.el7.x86_64                                                            1/9 
    Verifying  : libstemmer-0-2.585svn.el7.x86_64                                                       2/9 
    Verifying  : 1:v8-3.14.5.10-25.el7.x86_64                                                           3/9 
    Verifying  : gperftools-libs-2.6.1-1.el7.x86_64                                                     4/9 
    Verifying  : boost-program-options-1.53.0-27.el7.x86_64                                             5/9 
    Verifying  : mongodb-server-2.6.12-6.el7.x86_64                                                     6/9 
    Verifying  : 1:yaml-cpp-0.5.1-1.el7.2.x86_64                                                        7/9 
    Verifying  : boost-filesystem-1.53.0-27.el7.x86_64                                                  8/9 
    Verifying  : 14:libpcap-1.5.3-11.el7.x86_64                                                         9/9 

Installed:
    mongodb.x86_64 0:2.6.12-6.el7                    mongodb-server.x86_64 0:2.6.12-6.el7                   

Dependency Installed:
    boost-filesystem.x86_64 0:1.53.0-27.el7           boost-program-options.x86_64 0:1.53.0-27.el7          
    gperftools-libs.x86_64 0:2.6.1-1.el7              libpcap.x86_64 14:1.5.3-11.el7                        
    libstemmer.x86_64 0:0-2.585svn.el7                v8.x86_64 1:3.14.5.10-25.el7                          
    yaml-cpp.x86_64 1:0.5.1-1.el7.2                  

Complete!

4.3 CentOS系统上操作MongoDB数据库常用命令

[root@localhost ~]# systemctl status mongod                 # 查看系统上MongoDB数据库启动状态
● mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/usr/lib/systemd/system/mongod.service; disabled; vendor preset: disabled)
    Active: inactive (dead)
[root@localhost ~]# systemctl start mongod                  # 启动MongoDB数据库
[root@localhost ~]# systemctl status mongod                 # 再次查看MongoDB数据库的启动状态,显示已启动
● mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/usr/lib/systemd/system/mongod.service; disabled; vendor preset: disabled)
    Active: active (running) since Mon 2019-03-18 19:22:17 CST; 2s ago
    Process: 1393 ExecStart=/usr/bin/mongod $OPTIONS run (code=exited, status=0/SUCCESS)
    Main PID: 1395 (mongod)
    CGroup: /system.slice/mongod.service
            └─1395 /usr/bin/mongod --quiet -f /etc/mongod.conf run

Mar 18 19:22:17 localhost.localdomain systemd[1]: Starting High-performance, schema-free document-or......
Mar 18 19:22:17 localhost.localdomain mongod[1393]: about to fork child process, waiting until serve...ns.
Mar 18 19:22:17 localhost.localdomain mongod[1393]: forked process: 1395
Mar 18 19:22:17 localhost.localdomain systemd[1]: Started High-performance, schema-free document-ori...se.
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost ~]# systemctl stop mongod                   # 停止MongoDB
[root@localhost ~]# systemctl status mongod
● mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/usr/lib/systemd/system/mongod.service; disabled; vendor preset: disabled)
    Active: inactive (dead)

Mar 18 19:22:17 localhost.localdomain systemd[1]: Starting High-performance, schema-free document-or......
Mar 18 19:22:17 localhost.localdomain mongod[1393]: about to fork child process, waiting until serve...ns.
Mar 18 19:22:17 localhost.localdomain mongod[1393]: forked process: 1395
Mar 18 19:22:17 localhost.localdomain systemd[1]: Started High-performance, schema-free document-ori...se.
Mar 18 19:22:23 localhost.localdomain systemd[1]: Stopping High-performance, schema-free document-or......
Mar 18 19:22:23 localhost.localdomain systemd[1]: Stopped High-performance, schema-free document-ori...se.
Hint: Some lines were ellipsized, use -l to show in full.
[root@localhost ~]# systemctl enable mongod                 # 把MongoDB设置为开机自启动
Created symlink from /etc/systemd/system/multi-user.target.wants/mongod.service to /usr/lib/systemd/system/mongod.service.
[root@localhost ~]# systemctl disable mongod                # 取消MongoDB数据库开机自启动
Removed symlink /etc/systemd/system/multi-user.target.wants/mongod.service.

5.MongoDB的基础命令

数据库基本操作:

show dbs/show databases             # 查看所有数据库
use db_name                         # 切换数据库
db                                  # 查看当前数据库
db.dropDatabase()                   # 删除当前数据库

命令的基本操作:

db.createCollection(name,options)   # 手动创建集合
    options可配置选项为:
        capped:默认值为false表示集合大小不设置上限,值为true表示为集合大小设置上限
        size:当capped值为true时,需要指定参数,表示集合上限大小,当文档达到上限时,会将之前的数据覆盖,单位为字节
show collections                    # 查看所有集合
db.集合名称.drop()                   # 删除指定集合

向不存在的集合中第一次加入数据时,集合会自动被创建出来,也可以手动创建集合

示例:

[root@localhost ~]# mongo
MongoDB shell version v3.4.16
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.16
Server has startup warnings: 
2019-03-21T21:38:26.752+0800 I CONTROL  [initandlisten] 
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] 
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] 
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] 
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2019-03-21T21:38:26.753+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-03-21T21:38:26.754+0800 I CONTROL  [initandlisten] 
> show dbs                                  # 查看所有数据库
admin   0.000GB
local   0.000GB
quotes  0.000GB
> db.createCollection("study_test")         # 手动创建study_test集合,返回1表示集合创建成功
{ "ok" : 1 }
> use study_test                            # 使用study_test集合
switched to db study_test

6.MongoDB的数据类型

MongoDB中的数据类型有:

Object ID                   # 文档ID
String                      # 字符串,最常用,必须是有效的UTF-8
Boolean                     # 存储一个布尔值,true或false
Integer                     # 整数可以是32位或者64位,取决于服务器
Double                      # 存储浮点值
Arrays                      # 数组或列表,多个值存储到一个键
Object                      # 用于嵌入式的文档,即一个值为一个文档
Null                        # 存储Null值
Timestamp                   # 时间戳,表示从1970-1-1到现在的总秒数
Date                        # 存储当前日期或时间的UNIX时间格式

需要注意的点:

1.创建⽇期语句如下 :参数的格式为YYYY-MM-DD

例如:

> new Date("2018-12-12")
ISODate("2018-12-12T00:00:00Z")

2.每个⽂档都有⼀个_id属性,保证每个⽂档的唯⼀性.在向集合中写入文档时,可以⾃⼰设置文档的_id属性,如果没有手动指定,则MongoDB会为每个⽂档提供了⼀个唯一的_id, 类型为objectID

objectID是⼀个12字节的⼗六进制数:前4个字节为当前时间戳,接下来3个字节的机器ID,接下来的2个字节中MongoDB的服务进程id,最后3个字节是简单的增量值

例如:

> db.test_table01.insert({"name":"xiaowang","age":10})          # 向test_table01集合中插入一条数据
WriteResult({ "nInserted" : 1 })
> db.test_table01.find()                    # 打印test_table01中的所有数据
{ "_id" : ObjectId("5c939a4f4c9ce97c5b78a0da"), "name" : "xiaowang", "age" : 10 }
> db.test_table01.find().pretty()           # 格式化打印test_table01中的所有数据
{
        "_id" : ObjectId("5c939a4f4c9ce97c5b78a0da"),
        "name" : "xiaowang",
        "age" : 10
}
> db.test_table01.insert({name:"xiaohong",age:20})
WriteResult({ "nInserted" : 1 })
> db.test_table01.find()
{ "_id" : ObjectId("5c939a4f4c9ce97c5b78a0da"), "name" : "xiaowang", "age" : 10 }
{ "_id" : ObjectId("5c939adc4c9ce97c5b78a0db"), "name" : "xiaohong", "age" : 20 }
> db.test_table01.find().pretty()
{
        "_id" : ObjectId("5c939a4f4c9ce97c5b78a0da"),
        "name" : "xiaowang",
        "age" : 10
}
{
        "_id" : ObjectId("5c939adc4c9ce97c5b78a0db"),
        "name" : "xiaohong",
        "age" : 20
}
posted @ 2019-03-22 10:45  renpingsheng  阅读(940)  评论(0编辑  收藏  举报