MongoDB數據庫(一):基本操做

1.NoSQL的概念

"NoSQL"一詞最先於1998年被用於一個輕量級的關係數據庫的名字
隨着web2.0的快速發展,NoSQL概念在2009年被提了出來
NoSQL最多見的解釋是"non-relational","Not Only SQL"也被不少人接受,指的是非關係型數據庫python

2.關係型數據庫和非關係型的區別

關係型數據庫很強大,可是並不能很好的應付全部的場景.關係型數據庫的擴展性差,大數據下IO壓力大,表結構更改困難web

非關係型數據庫易擴展,大數據量高性能,靈活的數據模型,高可用sql

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的基礎命令

數據庫基本操做:mongodb

show dbs/show databases             # 查看全部數據庫
use db_name                         # 切換數據庫
db                                  # 查看當前數據庫
db.dropDatabase()                   # 刪除當前數據庫

命令的基本操做:shell

db.createCollection(name,options)   # 手動建立集合
    options可配置選項爲:
        capped:默認值爲false表示集合大小不設置上限,值爲true表示爲集合大小設置上限
        size:當capped值爲true時,須要指定參數,表示集合上限大小,當文檔達到上限時,會將以前的數據覆蓋,單位爲字節
show collections                    # 查看全部集合
db.集合名稱.drop()                   # 刪除指定集合

向不存在的集合中第一次加入數據時,集合會自動被建立出來,也能夠手動建立集合數據庫

示例:centos

[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
}
相關文章
相關標籤/搜索