天天看點

MongoDB簡單介紹以及基本指令

一、MongoDB簡介

1、MongoDB是什麼

  MongoDB 是一個基于分布式檔案存儲的資料庫。由 C++ 語言編寫。旨在為 WEB 應用提供可擴充的高性能資料存儲解決方案。MongoDB 是一個介于關系資料庫和非關系資料庫之間的産品,是非關系資料庫當中功能最豐富,最像關系資料庫的。他支援的資料結構非常松散,是類似json的bson格式,是以可以存儲比較複雜的資料類型。Mongo最大的特點是他支援的查詢語言非常強大,其文法有點類似于面向對象的查詢語言,幾乎可以實作類似關系資料庫單表查詢的絕大部分功能,而且還支援對資料建立索引MongoDB 将資料存儲為一個文檔,資料結構由鍵值(key=>value)對組成。MongoDB 文檔類似于 JSON 對象。字段值可以包含其他文檔,數組及文檔數組。文檔是MongoDB中資料的基本單元,非常類似于關系型資料庫管理系統中的行,但更具表現力!

2、MongoDB特點

MongoDB的提供了一個面向文檔存儲,操作起來比較簡單和容易。

你可以在MongoDB記錄中設定任何屬性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")來實作更快的排序。

你可以通過本地或者網絡建立資料鏡像,這使得MongoDB有更強的擴充性。

如果負載的增加(需要更多的存儲空間和更強的處理能力) ,它可以分布在計算機網絡中的其他節點上這就是所謂的分片。

Mongo支援豐富的查詢表達式。查詢指令使用JSON形式的标記,可輕易查詢文檔中内嵌的對象及數組。

MongoDb 使用update()指令可以實作替換完成的文檔(資料)或者一些指定的資料字段 。

Mongodb中的Map/reduce主要是用來對資料進行批量處理和聚合操作。

Map和Reduce。Map函數調用emit(key,value)周遊集合中所有的記錄,将key與value傳給Reduce函數進行處理。

Map函數和Reduce函數是使用Javascript編寫的,并可以通過db.runCommand或mapreduce指令來執行MapReduce操作。

GridFS是MongoDB中的一個内置功能,可以用于存放大量小檔案。

MongoDB允許在服務端執行腳本,可以用Javascript編寫某個函數,直接在服務端執行,也可以把函數的定義存儲在服務端,下次直接調用即可。

MongoDB支援各種程式設計語言:RUBY,PYTHON,JAVA,C++,PHP,C#等多種語言。

MongoDB安裝簡單。

3、NoSQL簡介

NoSQL(NoSQL = Not Only SQL ),意即"不僅僅是SQL"。在現代的計算系統上每天網絡上都會産生龐大的資料量。

這些資料有很大一部分是由關系資料庫管理系統(RDMBSs)來處理。 1970年 E.F.Codd's提出的關系模型的論文 "A relational model of data for large shared data banks",這使得資料模組化和應用程式程式設計更加簡單。通過應用實踐證明,關系模型是非常适合于客戶伺服器程式設計,遠遠超出預期的利益,今天它是結構化資料存儲在網絡和商務應用的主導技術。

NoSQL 是一項全新的資料庫革命性運動,早期就有人提出,發展至2009年趨勢越發高漲。NoSQL的擁護者們提倡運用非關系型的資料存儲,相對于鋪天蓋地的關系型資料庫運用,這一概念無疑是一種全新的思維的注入。

4、關系型資料庫遵循ACID規則

事務在英文中是transaction,和現實世界中的交易很類似,它有如下四個特性:

a、A (Atomicity) 原子性

原子性很容易了解,也就是說事務裡的所有操作要麼全部做完,要麼都不做,事務成功的條件是事務裡的所有操作都成功,隻要有一個操作失敗,整個事務就失敗,需要復原。

比如銀行轉賬,從A賬戶轉100元至B賬戶,分為兩個步驟:1)從A賬戶取100元;2)存入100元至B賬戶。這兩步要麼一起完成,要麼一起不完成,如果隻完成第一步,第二步失敗,錢會莫名其妙少了100元。

b、C (Consistency) 一緻性

一緻性也比較容易了解,也就是說資料庫要一直處于一緻的狀态,事務的運作不會改變資料庫原本的一緻性限制。

例如現有完整性限制a+b=10,如果一個事務改變了a,那麼必須得改變b,使得事務結束後依然滿足a+b=10,否則事務失敗。

c、I (Isolation) 獨立性

所謂的獨立性是指并發的事務之間不會互相影響,如果一個事務要通路的資料正在被另外一個事務修改,隻要另外一個事務未送出,它所通路的資料就不受未送出事務的影響。

比如現有有個交易是從A賬戶轉100元至B賬戶,在這個交易還未完成的情況下,如果此時B查詢自己的賬戶,是看不到新增加的100元的。

d、D (Durability) 持久性

持久性是指一旦事務送出後,它所做的修改将會永久的儲存在資料庫上,即使出現當機也不會丢失。

5、RDBMS vs NoSQL

RDBMS 

- 高度組織化結構化資料 

- 結構化查詢語言(SQL) (SQL) 

- 資料和關系都存儲在單獨的表中。 

- 資料操縱語言,資料定義語言 

- 嚴格的一緻性

- 基礎事務

NoSQL 

- 代表着不僅僅是SQL

- 沒有聲明性查詢語言

- 沒有預定義的模式

-鍵 - 值對存儲,列存儲,文檔存儲,圖形資料庫

- 最終一緻性,而非ACID屬性

- 非結構化和不可預知的資料

- CAP定理 

- 高性能,高可用性和可伸縮性

6、CAP定理(CAP theorem)

在計算機科學中, CAP定理(CAP theorem), 又被稱作 布魯爾定理(Brewer's theorem), 它指出對于一個分布式計算系統來說,不可能同時滿足以下三點:

一緻性(Consistency) (所有節點在同一時間具有相同的資料)

可用性(Availability) (保證每個請求不管成功或者失敗都有響應)

分隔容忍(Partition tolerance) (系統中任意資訊的丢失或失敗不會影響系統的繼續運作)

CAP理論的核心是:一個分布式系統不可能同時很好的滿足一緻性,可用性和分區容錯性這三個需求,最多隻能同時較好的滿足兩個。

是以,根據 CAP 原理将 NoSQL 資料庫分成了滿足 CA 原則、滿足 CP 原則和滿足 AP 原則三 大類:

CA - 單點叢集,滿足一緻性,可用性的系統,通常在可擴充性上不太強大。

CP - 滿足一緻性,分區容忍性的系統,通常性能不是特别高。

AP - 滿足可用性,分區容忍性的系統,通常可能對一緻性要求低一些。

7、NoSQL的優點/缺點

優點:

- 高可擴充性

- 分布式計算

- 低成本

- 架構的靈活性,半結構化資料

- 沒有複雜的關系

缺點:

- 沒有标準化

- 有限的查詢功能(到目前為止)

- 最終一緻是不直覺的程式

BASE:Basically Available, Soft-state, Eventually Consistent。 由 Eric Brewer 定義。

CAP理論的核心是:一個分布式系統不可能同時很好的滿足一緻性,可用性和分區容錯性這三個需求,最多隻能同時較好的滿足兩個。

BASE是NoSQL資料庫通常對可用性及一緻性的弱要求原則:

Basically Availble           --基本可用

Soft-state                --軟狀态/柔性事務。 "Soft state" 可以了解為"無連接配接"的, 而 "Hard state" 是"面向連接配接"的

Eventual Consistency         --最終一緻性 最終一緻性, 也是是 ACID 的最終目的。

MongoDB簡單介紹以及基本指令

注:上圖參考網上

二、MongoDB的Yum安裝方式

1、MonggoDB支援以下平台:

OS X 32-bit
OS X 64-bit
Linux 32-bit
Linux 64-bit
Windows 32-bit
Windows 64-bit
Solaris i86pc
Solaris 64
下載下傳位址: http://www.mongodb.org/downloads。
           

2、配置yum源

安裝epel源(版本較低),如下:

# yum list all | grep mongodb
libmongodb.i686                             2.4.14-1.el6                 epel   
libmongodb.x86_64                           2.4.14-1.el6                 epel   
libmongodb-devel.i686                       2.4.14-1.el6                 epel   
libmongodb-devel.x86_64                     2.4.14-1.el6                 epel   
mongodb.x86_64                              2.4.14-1.el6                 epel   
mongodb-server.x86_64                       2.4.14-1.el6                 epel   
nodejs-mongodb.noarch                       1.3.19-4.el6                 epel   
安裝:
#yum install mongodb -y
2.6版本yum源
#vi /etc/yum.repos.d/mongodb-org-2.6.repo
[mongodb-org-2.6]
name=MongoDB 2.6 Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1
安裝:
#yum --enablerepo=mongodb-org-3.4  install mongodb-org -y
3.4版本yum源
#vi /etc/yum.repos.d/mongodb-org-3.4.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=
 
這裡配置的是mongodb的3.4版本的yum源
開始安裝
#yum install -y mongodb-org
或者
#yum --enablerepo=mongodb-org-3.4 install mongodb-org -y
如果報錯将mongodb-org-3.4.repo中的https改為http!
如果繼續報錯如下:
GPG key retrieval failed: [Errno 14] Peer cert cannot be verified or peer cert invalid
将mongodb-org-3.4.repo中的gpgcheck和enabled值改為0 (有風險,測試環境可用)
檢視是否安裝成功
#which mongod
/usr/bin/mongod
檢視安裝了哪些軟體包:
#rpm -qa mongodb-*
mongodb-org-server-3.4.2-1.el6.x86_64
mongodb-org-mongos-3.4.2-1.el6.x86_64
mongodb-org-3.4.2-1.el6.x86_64
mongodb-org-shell-3.4.2-1.el6.x86_64
mongodb-org-tools-3.4.2-1.el6.x86_64
啟動MongoDB
service mongod start
Starting mongod: [  OK  ]
注:yum安裝好MongoDB之後,預設資料存放目錄是/var/lib/mongo,日志資料存放在/var/log/mongodb
目錄中
啟動後,檢視日志
#cat /var/log/mongodb/mongod.log 
2016-08-31T20:48:22.771+0800 I CONTROL  [main] ***** SERVER RESTARTED *****
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] MongoDB starting : pid=22171 port=27017 dbpath=/var/lib/mongo 64-bit host=elk
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] db version v3.4.2
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] git version: 3f76e40c105fc223b3e5aac3e20dcd026b83b38b
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] modules: none
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] build environment:
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten]     distmod: rhel62
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten]     distarch: x86_64
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten]     target_arch: x86_64
2016-08-31T20:48:22.776+0800 I CONTROL  [initandlisten] options: { config: "/etc/mongod.conf", net: { bindIp: "127.0.0.1", port: 27017 }, processManagement: { fork: true, pidFilePath: "/var/run/mongodb/mongod.pid" }, storage: { dbPath: "/var/lib/mongo", journal: { enabled: true } }, systemLog: { destination: "file", logAppend: true, path: "/var/log/mongodb/mongod.log" } }
2016-08-31T20:48:22.794+0800 I STORAGE  [initandlisten] 
2016-08-31T20:48:22.794+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2016-08-31T20:48:22.794+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2016-08-31T20:48:22.794+0800 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=424M,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-08-31T20:48:22.836+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 64000 files. Number of processes should be at least 32000 : 0.5 times number of files.
2016-08-31T20:48:22.837+0800 I CONTROL  [initandlisten] 
2016-08-31T20:48:22.842+0800 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/var/lib/mongo/diagnostic.data'
2016-08-31T20:48:22.849+0800 I INDEX    [initandlisten] build index on: admin.system.version properties: { v: 2, key: { version: 1 }, name: "incompatible_with_version_32", ns: "admin.system.version" }
2016-08-31T20:48:22.849+0800 I INDEX    [initandlisten]          building index using bulk method; build may temporarily use up to 500 megabytes of RAM
2016-08-31T20:48:22.849+0800 I INDEX    [initandlisten] build index done.  scanned 0 total records. 0 secs
2016-08-31T20:48:22.850+0800 I COMMAND  [initandlisten] setting featureCompatibilityVersion to 3.4
2016-08-31T20:48:22.850+0800 I NETWORK  [thread1] waiting for connections on port 27017
可以看到有幾個WARNING,檢視是否啟動成功了:
#netstat -tunlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      4678/sshd           
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      4759/master         
tcp        0      0 127.0.0.1:27017             0.0.0.0:*                   LISTEN      22171/mongod        
tcp        0      0 10.0.90.24:6379             0.0.0.0:*                   LISTEN      4809/redis-server 1 
tcp        0      0 :::22                       :::*                        LISTEN      4678/sshd           
tcp        0      0 ::1:25                      :::*                        LISTEN      4759/master         
# ps aux | grep mongod
mongod   22171  0.5  2.1 321852 41272 ?        Sl   20:48   0:03 /usr/bin/mongod -f /etc/mongod.conf
root     22206  0.0  0.0 103244   872 pts/1    S+   20:59   0:00 grep mongod
可以看到端口和程序都在,說明啟動成功了!
下面分析一下剛才日志中的幾個warning:、
第一個: WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
意思是:強烈建議使用帶WiredTiger存儲引擎的XFS檔案系統
XFS檔案系統:XFS一種高性能的日志檔案系統,最早于1993年,由Silicon Graphics為他們的IRIX作業系統而開發,
是IRIX 5.3版的預設檔案系統。2000年5月,Silicon Graphics以GNU通用公共許可證釋出這套系統的源代碼,之後
被移植到Linux 核心上。XFS 特别擅長處理大檔案,同時提供平滑的資料傳輸。
既然是warning說明不會影響mongodb的正常使用,隻是提醒你安裝mongodb最好使用ext4或者xfs檔案系統!
本人系統已經是ext4系統了!

第二個: WARNING: Access control is not enabled for the database.
意思是:未對資料庫啟用通路控制,對資料和配置的讀寫通路不受限制(危險的warning)

第三個:WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
#cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never
關閉指令:
#echo never > /sys/kernel/mm/transparent_hugepage/enabled

第四個:WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
需要将/sys/kernel/mm/transparent_hugepage/defrag設定為never
#cat /sys/kernel/mm/transparent_hugepage/defrag
[always] madvise never
關閉指令:
#echo never > /sys/kernel/mm/transparent_hugepage/defrag

第五個:WARNING: soft rlimits too low. rlimits set to 1024 processes, 64000 files. Number of processes should be at least 32000
設定ulimit
#vi /etc/security/limits.conf
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 32000
mongod hard nproc 32000
重新開機mongodb
#service mongod restart 
就不會報這個warning了,不過還是會有第一個和第二個warning,下面再介紹!
           

三、MongoDB使用

MongoDB預設是沒有設定鑒權的,業界大部分使用MongoDB的項目也沒有設定通路權限。這就意味着隻要知道MongoDB伺服器的端口,任何能通路到這台伺服器的人都可以查詢和操作MongoDB資料庫的内容。在一些項目當中,這種使用方式會被看成是一種安全漏洞。

1、第一次進入mongodb

可以使用MongoDB shell 來連接配接 MongoDB 伺服器。也可以使用 PHP 來連接配接 MongoDB。這裡我們會使用 MongoDB shell 來連接配接 Mongodb 服務,之後我們将會介紹如何通過php 來連接配接MongoDB服務。

标準 URI 連接配接文法:

mongodb://[username:[email protected]]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

mongodb:// 這是固定的格式,必須要指定。
username:[email protected] 可選項,如果設定,在連接配接資料庫伺服器之後,驅動都會嘗試登陸這個資料庫
host1 必須的指定至少一個host, host1 是這個URI唯一要填寫的。它指定了要連接配接伺服器的位址。如果要連接配接複制集,請指定多個主機位址。
portX 可選的指定端口,如果不填,預設為27017
/database 如果指定username:[email protected],連接配接并驗證登陸指定資料庫。若不指定,預設打開admin資料庫。
?options 是連接配接選項。如果不使用/database,則前面需要加上/。所有連接配接選項都是鍵值對name=value,鍵值對之間通過&或;(分号)隔開
           

使用shell的方式連接配接:

#mongo
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Server has startup warnings: 
2016-08-31T22:13:06.344+0800 I STORAGE  [initandlisten] 
2016-08-31T22:13:06.344+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2016-08-31T22:13:06.344+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2016-08-31T22:13:06.571+0800 I CONTROL  [initandlisten] 
2016-08-31T22:13:06.571+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2016-08-31T22:13:06.571+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2016-08-31T22:13:06.571+0800 I CONTROL  [initandlisten] 
> show databases;show databases;    #檢視資料庫
admin  0.000GB
local  0.000GB
>use admin    #切換資料庫
>switched to db admin
如下這種方式也可以
#mongo mongodb://127.0.0.1:27017
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2
Server has startup warnings: 
2016-09-02T21:07:29.630+0800 I STORAGE  [initandlisten] 
2016-09-02T21:07:29.630+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2016-09-02T21:07:29.630+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2016-09-02T21:07:29.978+0800 I CONTROL  [initandlisten] 
2016-09-02T21:07:29.978+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2016-09-02T21:07:29.978+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2016-09-02T21:07:29.978+0800 I CONTROL  [initandlisten] 
>
開啟MongoDB的web界面通路
MongoDB自帶一個微型的web管理資訊界面,需要修改/etc/mongod.conf中的一個配置項:
net:
  port: 27017
  bindIp: 10.0.90.24 
  http:
   enabled: true                  #設定為true
   RESTInterfaceEnabled: false    #設定為false
注:如果bindIp為127.0.0.1,隻能在本機使用curl檢視,無法再浏覽器通路!
重新開機mongodb,會自動監聽28017端口,然後通路,在浏覽器輸入:http://10.0.90.24:28017/,如下圖:
           
MongoDB簡單介紹以及基本指令

其中mongodbserver為mongodb伺服器的hostname,還有其他一些連接配接資訊!不過web界面方式使用不多。

注:如果設定了net.http.enabled等于true,并且開啟了security.authorization等于enabled,在浏覽器通路http://10.0.90.24:28017/的時候,會提示輸入使用者名和密碼,如下圖:

MongoDB簡單介紹以及基本指令

2、為MongoDB建立使用者管理者

  MongoDB中,每個資料庫的執行個體都可擁有多個使用者,安全檢查開啟後,隻要通過身份驗證的使用者才能夠進行資料的讀寫操作。admin(管理者)和local(本地)是兩個特殊的資料庫,它們當中的使用者可對任何資料庫進行操作。這兩個資料庫中的使用者可被看作是超級使用者。經認證後,管理者使用者可對任何資料庫進行讀寫,同僚能執行某些隻有管理者才能執行的指令,如listDatabases和shutDown。

  在預設情況下,mongod是監聽在127.0.0.1之上的,任何用戶端都可以直接連接配接27017,且沒有認證。這樣做的好處是,使用者可以即時上手,不用擔心被一堆配置弄的心煩意亂。然而壞處也是顯而易見,如果直接在公網伺服器上如此搭建MongoDB,那麼所有人都可以直接通路并修改資料庫資料了。

  預設情況下,mongod也是沒有管理者賬戶的。是以除非你在admin資料庫中使用db.addUser()指令添加了管理者帳号,且使用--auth參數啟動mongod,否則在資料庫中任何人都可以無需認證執行所有指令,包括delete和shutdown。此外,mongod還會預設監聽28017端口,同樣是綁定所有ip。這是一個mongod自帶的web監控界面。從中可以擷取到資料庫目前連接配接、log、狀态、運作系統等資訊。如果你開啟了--rest參數,甚至可以直接通過web界面查詢資料,執行mongod指令。

  其實MongoDB本身有非常詳細的安全配置準則,顯然開發者也是想到了,然而他是将安全的任務推給使用者去解決,這本身的政策就是偏向易用性的,對于安全性,則得靠邊站了。

注:每個資料庫都有自己的使用者,建立使用者的指令是db.createUser(),當你建立一個使用者時,該使用者就屬于你目前所在的資料庫。

  MongoDB有一個比較奇怪的設定是,即便是一個admin使用者,授權也必須在admin資料庫下進行,而不能在其他資料庫下進行。而授權之後admin使用者就可以在任何資料庫下進行任何操作了。當然資料庫級别的使用者在他自己的資料庫下授權之後是不能到其他資料庫進行操作的 

每個使用者包含三個要素:使用者名、密碼和角色清單。下面是一個例子:

{
user: "dbuser",
pwd : "dbpass",
roles: ["readWrite", "clusterAdmin"]
}
           

這個例子表示一個名為dbuser的使用者,它在目前的資料庫中擁有readWrite和clusterAdmin兩個角色。

注:MongoDB内置了很多角色,但要注意,不是每個資料庫的内置角色都一樣。其中admin資料庫就包含了一些其他資料庫所沒有的角色。熟悉Oracle的朋友都知道,資料庫使用者有兩種,一種是管理者,用來管理使用者;一種是普通使用者,用來通路資料。類似的,為MongoDB規劃使用者鑒權時,至少要規劃兩種角色:使用者管理者和資料庫使用者。如果搭建了分片或主從,可能還會要規劃資料庫架構管理者的角色,它們專門用來調整資料庫的分布式架構。

下面是一個建立使用者管理者的操作例子:

> use admin
switched to db admin
> db.createUser({user:"root",pwd:"test123",roles:["userAdminAnyDatabase"]})
Successfully added user: { "user" : "root", "roles" : [ "userAdminAnyDatabase" ] }
然後登陸測試一下
> use admin
switched to db admin
> db.auth("root","test123")
1
注:db.auth()方法傳回1表示登入成功。
檢視使用者
>show users;
{
        "_id" : "admin.root",
        "user" : "root",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
設定完後,MongoDB用戶端必須用正确的使用者名和密碼登入,才能在指定的資料庫中操作。
           

下面是一個如何建立資料庫使用者的例子:

首先保證你已經以使用者管理者的身份登入admin資料庫。然後用use指令切換到目标資料庫,同樣用db.createUser() 
指令來建立使用者,其中角色名為“readWrite”,普通的資料庫使用者角色有兩種,read和readWrite。顧名思義,
前者隻能讀取資料不能修改,後者可以讀取和修改。
> use admin
switched to db admin
> db.auth("root","test123")
1
> show dbs;
admin  0.000GB
local  0.000GB
test   0.000GB
> use test
switched to db test
> db
test
#建立一個名為testuser123的使用者,密碼設定為123456,如下:
> db.createUser({user:"testuser123",pwd:"123456,",roles:["readWrite"]})
Successfully added user: { "user" : "testuser123", "roles" : [ "readWrite" ] }
> db.auth("testuser123","123456,")
1    #認證通過
以上就實作了為test庫建立了一個普通使用者!!!
注意:普通使用者就算認證db.auth()通過之後,也沒有權限執行show dbs指令,隻能用db指令檢視目前資料庫!
           

3、在配置檔案中開啟mongodb連接配接認證功能

注:如果不開啟認證功能,任何人隻要可以ssh到mongodb的伺服器,都可以進行增删改查等操作,這樣
是很危險的。
在配置檔案mongod.conf中開啟,如下:
security:
  authorization: enabled
然後重新開機mongodb就開啟了認證功能,測試如下:
#mongo --host 10.0.90.24          #如果是監聽的127.0.0.1,就不需要加--host 參數了
MongoDB shell version v3.4.2
connecting to: mongodb://10.0.90.24:27017/
MongoDB server version: 3.4.2
> 
可以看到增加了認證功能,就不會提示上面提到的第一個和第二個WARNING了。
然後直接執行show dbs 看看會不會列出所有的資料庫
> show dbs
2017-02-13T11:54:45.562+0800 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13,
        "codeName" : "Unauthorized"
} :
[email protected]/mongo/shell/utils.js:25:13
[email protected]/mongo/shell/mongo.js:62:1
[email protected]/mongo/shell/utils.js:755:19
[email protected]/mongo/shell/utils.js:645:15
@(shellhelp2):1:1
> 
可以看到提示類似“not authorized on admin to execute command”說明如果不進行權限認證,就無
法進行其他操作,那麼我們進行認證,如下:
> use admin
switched to db admin
> db.auth("root","test123")
1
> show dbs;show dbs;
admin  0.000GB
local  0.000GB
test   0.000GB
說明認證通過,可以檢視所有的資料庫了!!!
一個例子:
#mongo --host 10.0.90.24         #進入mongodb
MongoDB shell version v3.4.2
connecting to: mongodb://10.0.90.24:27017/
MongoDB server version: 3.4.2
> use web
switched to db web
> db.auth("xlg","123456,")db.auth("xlg","123456,")
1
> show dbs;show dbs;        #根據提示可以看出普通使用者無法執行show dbs指令
2017-02-13T15:33:32.816+0800 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13,
        "codeName" : "Unauthorized"
} :
[email protected]/mongo/shell/utils.js:25:13
[email protected]/mongo/shell/mongo.js:62:1
[email protected]/mongo/shell/utils.js:755:19
[email protected]/mongo/shell/utils.js:645:15
@(shellhelp2):1:1
> db
web
> db.web.findOne()db.web.findOne()    #檢視資料
{ 
        "_id" : ObjectId("58a14e272fede9a9e553f929"),
        "name" : "james",
        "age" : "10"
}
> db.web.findOne({"name":"house"}) #檢視name等于house的資料
{
        "_id" : ObjectId("58a150492fede9a9e553f92a"),
        "name" : "curry",
        "age" : "9"
}
> use admin             #切換到admin庫
switched to db admin
> db.auth("root","test123")db.auth("root","test123")  #用管理者root認證
1
> db
admin
> use web             #切換到其他庫
switched to db web
> db
web
> db.web.findOne()db.web.findOne()         #檢視資料
{
        "_id" : ObjectId("58a14e272fede9a9e553f929"),
        "name" : "james",
        "age" : "10"
}
> db.web.findOne({"name":"house"})db.web.findOne({"name":"house"})
{
        "_id" : ObjectId("58a150492fede9a9e553f92a"),
        "name" : "curry",
        "age" : "9"
}
注意:如果想用admin超級使用者檢視除了admin之外的資料庫,先用普通使用者登入認證,然後切換到admin
庫,再進行認證後,才可以繼續其他操作。如上面的小例子
删除一個使用者
>db.system.users.remove({"user" : "test_user"});  删除一個test_user使用者
           

4、mongodb建立、删除、插入資料指令使用

> use test             #建立一個test資料庫
switched to db test
> db     #列出目前db名稱,為test
test
如果想列出所有資料庫,使用show dbs指令
> show dbs;
admin  0.000GB
local  0.000GB
但是并沒有看到剛才我們建立的test資料庫,那是因為test資料庫是空的,我們插入一條資料
> use test
switched to db test
> db
test
> db.test.insert({"name":"ceshishuju"})db.test.insert({"name":"ceshishuju"})
WriteResult({ "nInserted" : 1 })
> show dbsshow dbs
admin  0.000GB
local  0.000GB
test   0.000GB     #test 資料庫就顯示了
然後删除資料庫
> use test
switched to db test
> db.dropDatabase();
{ "dropped" : "test", "ok" : 1 }
> show dbs;show dbs;
admin  0.000GB
local  0.000GB    #可以看到test庫删掉了
基本檢視資料
> use test
switched to db test
> db.test.findOne()
{ "_id" : ObjectId("57c8206a8a704e1515c76e7b"), "name" : "ceshishuju" }
可以看到插入的資料這裡可以檢視到了!
多條件查詢,一個例子:
下面的示例等同于SQL語句的where name = "stephen" and age = 35
> db.test.find({"name":"stephen","age":35})
{ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35, "genda" : "male", "email" : "[email protected]" }
傳回指定的文檔鍵值對。下面的示例将隻是傳回name和age鍵值對。
> db.test.find({}, {"name":1,"age":1})
{ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35 }
指定不傳回的文檔鍵值對。下面的示例将傳回除name之外的所有鍵值對。
> db.test.find({}, {"name":0})
{ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "age" : 35, "genda" : "male", "email" : "[email protected]" }
網上關于mongodb查詢的部落格:
http://www.cnblogs.com/stephen-liu74/archive/2012/08/03/2553803.html
           

5、mongodb存儲引擎介紹

存儲引擎(Storage Engine)是MongoDB的核心元件,負責管理資料如何存儲在硬碟(Disk)和記憶體(Memory)上。從MongoDB 3.2 版本開始,MongoDB 支援多資料存儲引擎(Storage Engine),MongoDB支援的存儲引擎有:WiredTiger,MMAPv1和In-Memory。

從MongoDB 3.2版本開始,WiredTiger成為MongDB預設的Storage Engine,用于将資料持久化存儲到硬碟檔案中,WiredTiger提供文檔級别(Document-Level)的并發控制,檢查點(CheckPoint),資料壓縮和本地資料加密( Native Encryption)等功能。

MongoDB不僅能将資料持久化存儲到硬碟檔案中,而且還能将資料隻儲存到記憶體中;In-Memory存儲引擎用于将資料隻存儲在記憶體中,隻将少量的中繼資料和診斷日志(Diagnostic)存儲到硬碟檔案中,由于不需要Disk的IO操作,就能擷取索取的資料,In-Memory存儲引擎大幅度降低了資料查詢的延遲(Latency)

檢視MongoDB的預設存儲引擎:

#echo "db.serverStatus()"| mongo|grep wiredTiger
                "name" : "wiredTiger",
        "wiredTiger" : {
在mongod.conf中設定:
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
  engine: wiredTiger       #設定
           

WiredTiger和MMAPv1都用于持久化存儲資料,相對而言,WiredTiger比MMAPv1更新,功能更強大!

一篇很好地學習文章:http://www.cnblogs.com/ljhdo/archive/2016/10/30/4947357.html

四、MongoDB使用注意事項以及性能優化

1、Test every query in your application with explain().
使用explain()測試應用程式中的每個查詢。
MongoDB provides the ability to view how a query will be evaluated in the system, including which indexes are used and whether the query is covered. 
This capability is similar to the Explain Plan and similar features in relational databases. The feedback from explain() will help you understand
whether your query is performing optimally. 
2、Avoid scatter-gather queries. 避免分散-聚集查詢
In sharded systems, queries that cannot be routed to a single shard must be broadcast to multiple shards for evaluation. Because these queries 
involve multiple shards for each request they do not scale well as more shards are added.
3、Your operational applications should only read from primaries. 
你的操作應用程式隻應從主節點讀取 (待考證)
Updates are typically replicated to secondaries quickly, depending on network latency. However, reads on the secondaries will not be consistent
with reads on the primary. Note that the secondaries are not idle as they must process all writes replicated from the primary. To increase read 
capacity in your operational system consider sharding. Secondary reads can be useful for analytics and ETL applications as this approach will
isolate traffic from operational workloads. You may choose to read from secondaries if your application can tolerate eventual consistency. 
4、Use the most recent drivers from MongoDB. 使用MongoDB最新的驅動程式
MongoDB supports drivers for nearly a dozen languages. These drivers are engineered by the same team that maintains the database kernel. 
Drivers are updated more frequently than the database, typically every two months. Always use the most recent version of the drivers when 
possible. Install native extensions if available for your language. Join the MongoDB community mailing list to keep track of updates. 
5、Store all data for a record in a single document. 将記錄的所有資料存儲在單個文檔中
MongoDB provides ACID compliance at the document level. When data for a record is stored in a single document the entire record can
be retrieved in a single seek operation, which is very efficient. In some cases it may not be practical to store all data in a single 
document, or it may negatively impact other operations. Make the trade-offs that are best for your application. 
6、Avoid large documents. 避免使用大文檔
The maximum size for documents in MongoDB is 16 MB. In practice most documents are a few kilobytes or less. Consider documents more 
like rows in a table than the tables themselves. Rather than maintaining lists of records in a single document, instead make each
record a document. For large media items, such as video or images, consider using GridFS, a convention implemented by all the 
drivers that automatically stores the binary data across many smaller documents. 
7、Avoid large indexed arrays. 避免使用大型索引數組
Rather than storing a large array of items in an indexed field, store groups of values across multiple fields. Updates will be more efficient. 
8、Avoid unnecessarily long field names. 避免不必要的長字段名稱
Field names are repeated across documents and consume space. By using smaller field names your data will consume less space, which allows 
for a larger number of documents to fit in RAM. Note that with WiredTiger's native compression, long field names have less of an impact 
on the amount of disk space used but the impact on RAM is the same. 
9、Use caution when considering indexes on low-cardinality fields.
在考慮低基數字段上的索引時,請謹慎
Queries on fields with low cardinality can return large result sets. Avoid returning large result sets when possible. Compound indexes 
may include values with low cardinality, but the value of the combined fields should exhibit high cardinality. 
10、Eliminate unnecessary indexes. 取消不必要的索引。
Indexes are resource-intensive: even with compression enabled they consume RAM, and as fields are updated their associated indexes 
must be maintained, incurring additional disk I/O overhead. 
11、Remove indexes that are prefixes of other indexes. 
删除作為其他索引的字首的索引。
Compound indexes can be used for queries on leading fields within an index. For example, a compound index on last name, first name 
can be also used to filter queries that specify last name only. In this example an additional index on last name only is unnecessary; 
the compound index is sufficient for queries on last name as well as last name and first name. 
12、Use a compound index rather than index intersection. 
使用複合索引而不是索引交集
For best performance when querying via multiple predicates, compound indexes will generally be a better option. 
13、Avoid regular expressions that are not left anchored or rooted. 
避免沒有留下錨定或生根的正規表達式。
Indexes are ordered by value. Leading wildcards are inefficient and may result in full index scans. Trailing wildcards can be efficient 
if there are sufficient case-sensitive leading characters in the expression. 
14、Use index optimizations available in the WiredTiger storage engine. 
使用WiredTiger存儲引擎中提供的索引優化(3.0版本之後預設是WiredTiger引擎)
As discussed earlier, the WiredTiger engine compresses indexes by default. In addition, administrators have the flexibility to place 
indexes on their own separate volume, allowing for faster disk paging and lower contention. 
15、Use RAID10. 使用raid10
Most MongoDB deployments should use RAID-10. RAID-5 and RAID-6 have limitations and may not provide sufficient performance. 
RAID-0 provides good read and write performance, but insufficient fault tolerance. MongoDB's replica sets allow deployments 
to provide stronger availability for data, and should be considered with RAID and other factors to meet the desired availability SLA. 
16、Use multiple devices for different databases – WiredTiger. 
對不同的資料庫使用多個裝置 - WiredTiger。
Set directoryForIndexes so that indexes are stored in separate directories from collections and directoryPerDB to use a different 
directory for each database. The various directories can then be mapped to different storage devices, thus increasing overall 
throughput. Note that using different storage devices will affect your ability to create snapshot-style backups of your data, 
since the files will be on different devices and volumes.
17、Use EXT4 or XFS file systems; avoid EXT3. 
避免使用ext3檔案系統,使用ext4或者xfs檔案系統
EXT3 is quite old and is not optimal for most database workloads. For example, MMAPv1 preallocates space for data. 
In EXT3 preallocation will actually write 0s to the disk to allocate the space, which is time consuming. In EXT4 and XFS 
preallocation is performed as a logical operation, which is much more efficient. With the WiredTiger storage engine, use 
of XFS is strongly recommended to avoid performance issues that have been observed when using EXT4 with WiredTiger.
           

五、MongonDB 3.4.2版本配置檔案參數詳解

官網連結位址:

https://docs.mongodb.com/manual/reference/configuration-options/

注:配置參數是分級式的,比如net.http.RESTInterfaceEnabled其實在mongodb.conf中配置為:
net:
  port: 27017
  bindIp: 127.0.0.1  
  http:
   enabled: true
   RESTInterfaceEnabled: false
所有下面都以net.http.RESTInterfaceEnabled這種方式介紹
參數類型一共三種:
string    字元串
boolean   布爾型 false/true
integer   整形
1、systemLog 選項如下:
systemLog.verbosity     --用法:verbosity: <integer>
日志檔案輸出的級别,越大級别越低,預設是0 

systemLog.quiet         --用法: quite: boolean
在quite模式下會限制輸出資訊:
資料庫指令輸出,副本集活動,連接配接接受事件,連接配接關閉事件。

systemLog.traceAllExceptions     --用法:traceAllExceptions: boolean
列印用于調試的詳細資訊。 用于其他日志記錄以進行支援相關的故障排除。

systemLog.syslogFacility         --用法:syslogFacility: string,預設為user
指定syslog日志資訊的裝置級别,需要指定--syslog來使用這個選項。

systemLog.logAppend      --用法:logAppend: boolean
是否啟用追加日志

systemLog.destination    --用法:destination:string ,預設為file
指定一個檔案或syslog。如果指定為檔案,必須同時指定systemLog.path

systemLog.path           --用法:path: string 比如:/var/log/mongodb/mongod.log
日志路徑

systemLog.logRotate      --用法:logRotate: string ,預設值為rename,另一個是reopen
可以實作rotage日志,實作日志切割

systemLog.timeStampFormat   --用法:timeStampFormat: string 預設值為 iso8601-local
日志消息中時間戳的時間格式。還有ctime、iso8601-utc格式

2、storage 選項用法:
範例:
storage:
   dbPath: <string>
   indexBuildRetry: <boolean>
   repairPath: <string>
   journal:
      enabled: <boolean>
      commitIntervalMs: <num>
   directoryPerDB: <boolean>
   syncPeriodSecs: <int>
   engine: <string>
   mmapv1:
      preallocDataFiles: <boolean>
      nsSize: <int>
      quota:
         enforced: <boolean>
         maxFilesPerDB: <int>
      smallFiles: <boolean>
      journal:
         debugFlags: <int>
         commitIntervalMs: <num>
   wiredTiger:
      engineConfig:
         cacheSizeGB: <number>
         journalCompressor: <string>
         directoryForIndexes: <boolean>
      collectionConfig:
         blockCompressor: <string>
      indexConfig:
         prefixCompression: <boolean>
   inMemory:
      engineConfig:
         inMemorySizeGB: <number>
具體參數的解釋:
storage.dbPath     --用法:dbPath: string 預設是/data/db(linux) ;\data\db (windows)
注意:如果是yum安裝的mongodb,預設是/var/lib/mongo
mongodb資料存儲的路徑

storage.indexBuildRetry   --用法:indexBuildRetry: boolean 預設值是true
指定資料庫在索引建立過程中停止,重新開機後是否重建立立索引。

storage.repairPath        --用法:repairPath: string  預設值是:A _tmp_repairDatabase_<num> ( directory under the dbPath. )
在--repair操作期間MongoDB将使用的工作目錄。當--repair結束後,storage.repairPath 目錄變為空
注:storage.repairPath設定僅可用于mongod。

storage.journal.enabled           --用法:journal.enabled: boolean 
64bit作業系統預設為true,32bit作業系統預設為false
啟用或禁用持久性日志以確定資料檔案保持有效和可恢複,此選項僅在您指定--dbpath選項時适用。

storage.journal.commitIntervalMs  --用法:journal.commitIntervalMs: number
mongod程序在日志操作之間允許的最大時間(以毫秒為機關),較低的值會增加日志的持久性,但會降低磁盤性能。
範圍是1-500,預設值是100 毫秒。

storage.directoryPerDB            --用法:directoryPerDB: boolean 預設值時false
當為true時,MongoDB使用單獨的目錄來存儲每個資料庫的資料,目錄位于storage.dbPath目錄下,每個子目錄名稱對應于資料庫名稱。

storage.syncPeriodSecs            --用法:syncPeriodSecs: number 預設為60,不要設定為0
MongoDB通過fsync操作将資料重新整理到資料檔案之前可以經過的時間量。
特别注意:不要在生産系統上設定此值

storage.engine                    --用法: engine: wiredTiger 預設值為wiredTiger
設定mongodb的存儲引擎。還有mmapv1和inMemory

storage.wiredTiger.engineConfig.cacheSizeGB  --用法:cacheSizeGB: float
WiredTiger将用于所有資料的内部緩存的最大大小。值的範圍可以從256MB到10TB,可以是浮點數。 此外,預設值也已更改。
從3.4開始,WiredTiger内部緩存預設使用以下兩者中較大的一個:
50% of RAM minus 1 GB(50%的RAM減去1 GB), or 256 MB.

3、net 選項用法:
net:
   port: <int>
   bindIp: <string>
   maxIncomingConnections: <int>
   wireObjectCheck: <boolean>
   ipv6: <boolean>
   unixDomainSocket:
      enabled: <boolean>
      pathPrefix: <string>
      filePermissions: <int>
   http:
      enabled: <boolean>
      JSONPEnabled: <boolean>
      RESTInterfaceEnabled: <boolean>
   ssl:
      sslOnNormalPorts: <boolean>  # deprecated since 2.6
      mode: <string>
      PEMKeyFile: <string>
      PEMKeyPassword: <string>
      clusterFile: <string>
      clusterPassword: <string>
      CAFile: <string>
      CRLFile: <string>
      allowConnectionsWithoutCertificates: <boolean>
      allowInvalidCertificates: <boolean>
      allowInvalidHostnames: <boolean>
      disabledProtocols: <string>
      FIPSMode: <boolean>
net.port     --用法  port: integer   預設值是27017
mongodb監聽的端口

net.bindIp   --用法  bindIp: string  預設值是127.0.0.1
mongodb監聽的ip位址,也可以自定義

net.maxIncomingConnections   --用法:maxIncomingConnections: integer 預設值是65536
mongos或mongod将接受的最大并發連接配接數,如果此設定高于作業系統配置的最大連接配接跟蹤門檻值,則此設定不起作用。

net.wireObjectCheck    --用法:wireObjectCheck: boolean  預設值是true
為true時,mongod或mongos執行個體驗證用戶端收到的所有請求,以防止用戶端将錯誤格式或無效的BSON插入到MongoDB資料庫中。 
注意:對于具有高度子文檔嵌套的對象,net.wireObjectCheck對性能有輕微影響。

net.http.enabled       --用法:enabled: boolean   預設值是false
啟用或禁用HTTP接口。 啟用接口可能會增加網絡暴露。

net.http.RESTInterfaceEnabled  --用法:RESTInterfaceEnabled: boolean,預設為false
即使http接口選項關閉,打開也會暴露http接口,會導緻更多的不安全因素。不過開啟為true可以在
mongodb的web頁面通路List all commands 頁面!

net.unixDomainSocket.enabled   --用法 unixDomainSocket.enabled: boolean  預設值是true
在UNIX域套接字上啟用或禁用偵聽。 net.unixDomainSocket.enabled僅适用于基于Unix的系統。

4、security 選項
security:
   keyFile: <string>
   clusterAuthMode: <string>
   authorization: <string>
   transitionToAuth: <boolean>
   javascriptEnabled:  <boolean>
   redactClientLogData: <boolean>
   sasl:
      hostName: <string>
      serviceName: <string>
      saslauthdSocketPath: <string>
   enableEncryption: <boolean>
   encryptionCipherMode: <string>
   encryptionKeyFile: <string>
   kmip:
      keyIdentifier: <string>
      rotateMasterKey: <boolean>
      serverName: <string>
      port: <string>
      clientCertificateFile: <string>
      clientCertificatePassword: <string>
      serverCAFile: <string>
   ldap:
      servers: <string>
      bind:
         method: <string>
         saslMechanism: <string>
         queryUser: <string>
         queryPassword: <string>
         useOSDefaults: <boolean>
      transportSecurity: <string>
      timeoutMS: <int>
      userToDNMapping: <string>
      authz:
         queryTemplate: <string>

security.keyFile    --用法:keyFile: string 
密鑰檔案的路徑,該檔案存儲MongoDB執行個體用于在分片叢集或副本集中彼此進行身份驗證的共享密鑰
keyFile意味着security.authorization!

security.clusterAuthMode   --用法: clusterAuthMode: string 預設值是keyFile
用于叢集身份驗證的身份驗證模式

security.authorization    --用法:authorization: string  預設值是disabled
啟用或禁用基于角色的通路控制(RBAC)以管理每個使用者對資料庫資源和操作的通路。
enabled: 使用者隻能通路已為其授予了權限的資料庫資源和操作。
diabled: 使用者可以通路任何資料庫并執行任何操作

security.transitionToAuth     --用法:transitionToAuth: boolean 預設值是false
3.4版本新的功能,允許mongod或mongos接受和建立到部署中的其他mongod和mongos執行個體的已驗證和未驗證的連接配接

security.javascriptEnabled    --用法:javascriptEnabled: boolean 預設值是true
啟用或禁用伺服器端JavaScript執行,禁用時,不能使用執行伺服器端執行JavaScript代碼的操作,例如$ where查詢運算符,mapReduce指令和db.collection.mapReduce()方法,group指令和db.collection.group()方法 。

5、setParameter 選項
設定MongoDB伺服器參數中描述的MongoDB參數或參數
要在YAML配置檔案中設定參數,請使用以下格式:
setParameter:
   <parameter1>: <value1>
   <parameter2>: <value2>

例如,要在配置檔案中指定enableLocalhostAuthBypass
setParameter:
   enableLocalhostAuthBypass: false
   
6、operationProfiling   選項
operationProfiling:
   slowOpThresholdMs: <int>
   mode: <string>

operationProfiling.slowOpThresholdMs  --用法:slowOpThresholdMs: integer 預設值是100
資料庫概要分析器認為查詢速度緩慢的門檻值(以毫秒為機關),MongoDB将所有慢查詢記錄到日志中,即使資料庫分析器關閉
當分析器打開時,它将寫入system.profile集合   
   
operationProfiling.mode    --用法:mode: string 預設值是 off
資料庫概要分析的級别,它将有關操作性能的資訊插入到system.profile集合中。它的值有off、slowOp、all
注意:資料庫分析可能會影響資料庫性能。 僅在仔細考慮後才啟用此選項
   
7、replication 選項
replication:
   oplogSizeMB: <int>
   replSetName: <string>
   secondaryIndexPrefetch: <string>
   enableMajorityReadConcern: <boolean>   
   
replication.oplogSizeMB   --用法:oplogSizeMB: integer 
複制記錄檔的最大大小(以兆位元組為機關),例如:oplog。mongod程序基于可用的最大空間量建立oplog
對64bit系統而言,oplog通常是可用磁盤空間的5%,一旦mongod第一次建立oplog,更改replication.oplogSizeMB選項将不會影響oplog的大小  

replication.replSetName  --用法: replSetName: string 
mongod所屬的副本集的名稱。 副本集中的所有主機必須具有相同的集名稱。如果應用程式連接配接到多個副本集,則每個副本集應具有不同的名稱。 某些驅動程式按副本集名稱對副本集連接配接進行分組。   

replication.secondaryIndexPrefetch --用法:secondaryIndexPrefetch: string 預設值是all
存儲引擎特定功能:
replication.secondaryIndexPrefetch僅适用于mmapv1存儲引擎。

replication.enableMajorityReadConcern  --用法:  enableMajorityReadConcern: boolean 預設是false
啟用“多數”的讀取關注級别。 
   
8、sharding 選項
sharding:
   clusterRole: <string>
   archiveMovedChunks: <boolean>

sharding.clusterRole    --用法:clusterRole: string 
mongodb執行個體在分片叢集中具有的角色。有2個值,如下:
configsvr:将此執行個體作為配置伺服器啟動。 預設情況下,執行個體在端口27019上啟動。
shardsvr: 将此執行個體作為分片啟動。 預設情況下,執行個體在端口27018上啟動。
   
sharding.archiveMovedChunks  --用法: archiveMovedChunks:boolean
在塊遷移期間,分片不儲存從分片遷移的文檔。   

9、auditLog 選項  
僅在MongoDB Enterprise中可用
auditLog:
   destination: <string>
   format: <string>
   path: <string>
   filter: <string>   
     
還有很多其他參數,這裡不一一介紹了!
           

不足之處,請多多指出!