1. 程式人生 > >CentOS7安裝MongoDB及基礎操作

CentOS7安裝MongoDB及基礎操作

安裝環境說明

系統環境說明
[[email protected] ~]# cat /etc/redhat-release 
CentOS Linux release 7.4.1708 (Core) 
[[email protected] ~]# uname -r
3.10.0-693.el7.x86_64
[[email protected] ~]# hostname -I
192.168.174.200 192.168.122.1
軟體版本
https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.6.3.tgz

安裝工作

建立使用者
groupadd -g 800 mongodb
useradd  -u 806 -g mongodb  mongodb
修改密碼
echo 123456 |passwd --stdin mongodb
建立目錄
mkdir -p /usr/local/mongodb/27017/   &&\
cd  /usr/local/mongodb/27017/   &&\
mkdir  -p  bin  conf  log  data
下載程式
cd  /usr/local/mongodb/27017/
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-3.6.3.tgz
解壓程式
tar xf  mongodb-linux-x86_64-rhel70-3.6.3.tgz
cd mongodb-linux-x86_64-rhel70-3.6.3/bin/ &&\
cp * /usr/local/mongodb/27017/bin
修改程式屬性
chown -R mongodb:mongodb /usr/local/mongodb/27017
設定環境變數
su - mongod

cat >> .bash_profile <<'EOF'
export PATH=/usr/local/mongodb/27017/bin:$PATH
EOF
source .bashprofile
如提示.bashprofile不存在,執行vim .bashprofile即可

至此,安裝工作完成

管理MongoDB

啟動:mongod --dbpath=/usr/local/mongodb/27017/data --logpath=/usr/local/mongodb/27017/log/mongodb.log --port=27017 --logappend 
關閉:mongod --shutdown  --dbpath=/usr/local/mongodb/27017/data --logpath=/usr/local/mongodb/27017/log/mongodb.log --port=27017 --logappend 
 引數說明

引數

引數說明

--dbpath    

資料存放路徑

--logpath   

日誌檔案路徑

--logappend 

日誌輸出方式

--port      

啟用埠號

--fork      

在後臺執行

--auth      

是否需要驗證許可權登入(使用者名稱和密碼)

--bind_ip   

限制訪問的ip

--shutdown

關閉資料庫

--logpath 日誌檔案路徑
--master 指定為主機器
--slave 指定為從機器
--source 指定主機器的IP地址
--pologSize 指定日誌檔案大小不超過64M.因為resync是非常操作量大且耗時,最好通過設定一個足夠大的oplogSize來避免resync(預設的 oplog大小是空閒磁碟大小的5%)。
--logappend 日誌檔案末尾新增
--port 啟用埠號
--fork 在後臺執行
--only 指定只複製哪一個資料庫
--slavedelay 指從複製檢測的時間間隔
--auth 是否需要驗證許可權登入(使用者名稱和密碼)
 
 
-h [ --help ]             show this usage information
--version                 show version information
-f [ --config ] arg       configuration file specifying additional options
--port arg                specify port number
--bind_ip arg             local ip address to bind listener - all local ips
                           bound by default
-v [ --verbose ]          be more verbose (include multiple times for more
                           verbosity e.g. -vvvvv)
--dbpath arg (=/data/db/) directory for datafiles    指定資料存放目錄
--quiet                   quieter output   靜默模式
--logpath arg             file to send all output to instead of stdout   指定日誌存放目錄
--logappend               appnd to logpath instead of over-writing 指定日誌是以追加還是以覆蓋的方式寫入日誌檔案
--fork                    fork server process   以建立子程序的方式執行
--cpu                     periodically show cpu and iowait utilization 週期性的顯示cpu和io的使用情況
--noauth                  run without security 無認證模式執行
--auth                    run with security 認證模式執行
--objcheck                inspect client data for validity on receipt 檢查客戶端輸入資料的有效性檢查
--quota                   enable db quota management   開始資料庫配額的管理
--quotaFiles arg          number of files allower per db, requires --quota 規定每個資料庫允許的檔案數
--appsrvpath arg          root directory for the babble app server 
--nocursors               diagnostic/debugging option 除錯診斷選項
--nohints                 ignore query hints 忽略查詢命中率
--nohttpinterface         disable http interface 關閉http介面,預設是28017
--noscripting             disable scripting engine 關閉指令碼引擎
--noprealloc              disable data file preallocation 關閉資料庫檔案大小預分配
--smallfiles              use a smaller default file size 使用較小的預設檔案大小
--nssize arg (=16)        .ns file size (in MB) for new databases 新資料庫ns檔案的預設大小
--diaglog arg             0=off 1=W 2=R 3=both 7=W+some reads 提供的方式,是隻讀,只寫,還是讀寫都行,還是主要寫+部分的讀模式
--sysinfo                 print some diagnostic system information 列印系統診斷資訊
--upgrade                 upgrade db if needed 如果需要就更新資料庫
--repair                  run repair on all dbs 修復所有的資料庫
--notablescan             do not allow table scans 不執行表掃描
--syncdelay arg (=60)     seconds between disk syncs (0 for never) 系統同步重新整理磁碟的時間,預設是60s
 
Replication options:
--master              master mode 主複製模式
--slave               slave mode 從複製模式
--source arg          when slave: specify master as <server:port> 當為從時,指定主的地址和埠
--only arg            when slave: specify a single database to replicate 當為從時,指定需要從主複製的單一庫
--pairwith arg        address of server to pair with
--arbiter arg         address of arbiter server 仲裁伺服器,在主主中和pair中用到
--autoresync          automatically resync if slave data is stale 自動同步從的資料
--oplogSize arg       size limit (in MB) for op log 指定操作日誌的大小
--opIdMem arg         size limit (in bytes) for in memory storage of op ids指定儲存操作日誌的記憶體大小
 
Sharding options:
--configsvr           declare this is a config db of a cluster 指定shard中的配置伺服器
--shardsvr            declare this is a shard db of a cluster 指定shard伺服器
登入資料庫
mongo
使用配置檔案方式管理資料庫
cd /usr/local/mongodb/27017/conf

vim mongodb.conf 

dbpath=/usr/local/mongodb/27017/data
logpath=/usr/local/mongodb/27017/log/mongodb.log
port=27017
logappend=1
使用配置檔案的啟動和關閉
啟動:mongod -f mongodb.conf 
關閉:mongod -f mongodb.conf  --shutdown
使用配置檔案後臺執行
mongod -f mongodb.conf & 
3.X 版本官方推薦使用YAML格式配置檔案
vim  mongodb.yaml

systemLog:
   destination: file
   path: "/usr/local/mongodb/27017/log/mongodb.log"
   logAppend: true
storage:
   journal:
      enabled: true
   dbPath: "/usr/local/mongodb/27017/data"
net:
   port: 27017
啟動:mongod -f mongodb.yaml 
後臺:mongod -f mongodb.yaml &  
關閉:mongod -f mongodb.yaml  --shutdown
在資料庫中關閉資料庫
mongo
use admin
db.shutdownServer()
注:

mongod程序收到SIGINT訊號或者SIGTERM訊號,會做一些處理

> 關閉所有開啟的連線

> 將記憶體資料強制重新整理到磁碟

> 當前的操作執行完畢

> 安全停止

切忌kill -9

資料庫直接關閉,資料丟失,資料檔案損失,修復資料庫(成本高,有風險)
使用kill命令關閉程序

$ kill -2 PID
  原理:-2表示向mongod程序傳送SIGINT訊號。
或
$ kill -4 PID
  原理:-4表示向mognod程序傳送SIGTERM訊號。
使用指令碼管理服務
vim /etc/init.d/mongod
#!/bin/bash
#
#MongoDB服務管理
#################################
  
MONGODIR=/usr/local/mongodb/27017/
MONGOD=$MONGODIR/bin/mongod
MONGOCONF=$MONGODIR/conf/mongodb.conf
InfoFile=/tmp/start.mongo

. /etc/init.d/functions 

status(){
  PID=`awk 'NR==2{print $NF}' $InfoFile`
  Run_Num=`ps -p $PID|wc -l`
  if [ $Run_Num -eq 2 ]; then
    echo "MongoDB is running"
  else 
    echo "MongoDB is shutdown"
    return 3
  fi
}
 
start() {
  status &>/dev/null
  if [ $? -ne 3 ];then 
    action "啟動MongoDB,服務執行中..."  /bin/false 
    exit 2
  fi
  sudo su - mongodb -c "$MONGOD -f $MONGOCONF" >$InfoFile 2>/dev/null 
  if [ $? -eq 0 ];then 
    action "啟動MongoDB"  /bin/true
  else
    action "啟動MongoDB"  /bin/false
  fi
}

stop() {
  sudo su - mongodb -c "$MONGOD -f $MONGOCONF --shutdown"  &>/dev/null
  if [ $? -eq 0 ];then
    action "停止MongoDB"  /bin/true
  else 
    action "停止MongoDB"  /bin/false
  fi 
}
 
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    sleep 2
    start
    ;;
  status)
    status
    ;;
   *)
   echo $"Usage: $0 {start|stop|restart|status}"
   exit 1
esac

MongDB基礎操作

查詢操作

連線資料庫
[[email protected] ~]# mongo 192.168.174.200:27017/admin
MongoDB shell version v3.4.13
connecting to: mongodb://192.168.174.200:27017/admin
MongoDB server version: 3.4.13
Server has startup warnings: 
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] 
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] 
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] 
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] 
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2018-04-09T01:23:25.364+0800 I CONTROL  [initandlisten] 
> db
admin
檢視資料庫版本
> db.version()
3.4.13
> 
切換資料庫
> use test;
switched to db test
> db
test
顯示當前資料庫
> db
test
> db.getName();
test
檢視所有資料庫
> show dbs;
admin  0.000GB
local  0.000GB
> show databases;
admin  0.000GB
local  0.000GB
檢視當前資料庫機器的連線地址
> db.getMongo()
connection to 192.168.174.200:27017

管理操作

建立資料庫
> use mydb;
switched to db mydb

說明

建立資料庫:

當use的時候,系統就會自動建立一個數據庫。

如果use之後沒有建立任何集合。系統就會刪除這個資料庫。
> show dbs;
admin  0.000GB
local  0.000GB
mydb   0.000GB
> use mydbs;
switched to db mydbs
> db.dropDatabase()
{ "ok" : 1 }

刪除資料庫
> use mydbs;
switched to db mydbs
> db.dropDatabase()
{ "ok" : 1 }

說明

刪除資料庫:
  如果沒有選擇任何資料庫,會刪除預設的test資料庫
建立集合

方法一:

> db.createCollection('a')
{ "ok" : 1 }
> db.createCollection('b')
{ "ok" : 1 }

檢視集合

> show collections
a
b
> show getCollectionNames()
2018-04-09T16:41:33.145+0800 E QUERY    [thread1] Error: don't know how to show [getCollectionNames()] :
[email protected]/mongo/shell/utils.js:919:11
[email protected]/mongo/shell/utils.js:672:15
@(shellhelp2):1:1
> db.getCollectionNames();
[ "a", "b" ]
> 

方法二:

說明:插入一個文件的時候,一個集合就會自動建立。
> db.c.insert({name:'test1','age':123})
WriteResult({ "nInserted" : 1 })
> db.c.insert({address:'haerbin'})
WriteResult({ "nInserted" : 1 })

檢視集合內容

> db.c.find()
{ "_id" : ObjectId("5acb28b94a893f4e9544610e"), "name" : "test1", "age" : 123 }
{ "_id" : ObjectId("5acb29444a893f4e9544610f"), "address" : "haerbin" }
> 

重新命名集合

> db.c.renameCollection("d")
{ "ok" : 1 }
> show collections;
a
b
d
> 

刪除集合

> db.a.drop();
true
> show collections;
b
d
> 

批量插入500行資料

> for(i=0;i<10000;i++){ db.log.insert({"uid":i,"name":"mongodb","age":6,"date":new Date()}); }
WriteResult({ "nInserted" : 1 })
> db.log.find();

注:預設每頁顯示20條記錄,當顯示不下的的情況下,可以用it迭代命令查詢下一頁資料。

> DBQuery.shellBatchSize=50;    # 每頁顯示50條記錄
50 
> db.log.findOne()            # 檢視第1條記錄
> db.log.count()              # 查詢總的記錄數
> db.log.find({uid:100});    # 查詢UUID為100的資料

MongoBD中使用者管理

使用者許可權說明

許可權

說明

Read                

允許使用者讀取指定資料庫

readWrite           

允許使用者讀寫指定資料庫

dbAdmin             

允許使用者在指定資料庫中執行管理函式,如索引建立、刪除,檢視統計或訪問system.profile

userAdmin           

允許使用者向system.users集合寫入,可以找指定資料庫裡建立、刪除和管理使用者

clusterAdmin        

只在admin資料庫中可用,賦予使用者所有分片和複製集相關函式的管理許可權。

readAnyDatabase     

只在admin資料庫中可用,賦予使用者所有資料庫的讀許可權

readWriteAnyDatabase

只在admin資料庫中可用,賦予使用者所有資料庫的讀寫許可權

userAdminAnyDatabase

只在admin資料庫中可用,賦予使用者所有資料庫的userAdmin許可權

dbAdminAnyDatabase  

只在admin資料庫中可用,賦予使用者所有資料庫的dbAdmin許可權。

root                

只在admin資料庫中可用。超級賬號,超級許可權

更多關於使用者許可權的說明參照:https://docs.mongodb.com/manual/core/security-built-in-roles/

建立使用者語法

{
user: "<name>", 
pwd: "<cleartext password>", 
customData: { <any information> }, 
roles: [ 
{ role: "<role>", 
db: "<database>" } | "<role>", 
... 
] 
}

語法說明

user欄位:使用者的名字;

pwd欄位:使用者的密碼;

cusomData欄位:為任意內容,例如可以為使用者全名介紹;

roles欄位:指定使用者的角色,可以用一個空陣列給新使用者設定空角色;

roles 欄位:可以指定內建角色和使用者定義的角色。
建立管理員使用者

進入管理資料庫

use admin

建立管理員使用者,root許可權

db.createUser(
  {
    user: "root",
    pwd: "root",
    roles: [ { role: "root", db: "admin" } ]
  }
)  

注意

建立管理員角色使用者的時候,必須到admin下建立。
刪除的時候也要到相應的庫下操作。

檢視建立完使用者的collections

 > show tables; 
system.users  # 使用者存放位置
system.version
檢視建立的管理員使用者
> show users
{
        "_id" : "admin.root",
        "user" : "root",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}
> 

驗證使用者是否可用

> db.auth("root","root")
1  # 返回 1 即為成功

建立完使用者後在配置檔案中開啟使用者驗證

cat >>/usr/local/mongodb/27017/conf/mongodb.yaml<<-'EOF'
security:
  authorization: enabled
EOF	

SQL與MongoDB語言對比

SQL語言與CRUD語言對照 

SQL Schema Statements

MongoDB Schema Statements

CREATE TABLE users (

id MEDIUMINT NOT NULL

AUTO_INCREMENT,

user_id Varchar(30),

age Number,

status char(1),

PRIMARY KEY (id)

)

Implicitly created on first insert() operation. The primary

key _idis automatically added if _id field is not specified.

db.users.insert( {

user_id: "abc123",

age: 55,

status: "A"

} )

However, you can also explicitly create a collection:

db.createCollection("users")

ALTER TABLE users

ADD join_date DATETIME

在Collection 級沒有資料結構概念。然而在 document級,可以通過$set在

update操作新增列到文件中。

db.users.update(

{ },

{ $set: { join_date: new Date() } },

{ multi: true }

)

ALTER TABLE users

DROP COLUMN join_date

在Collection 級沒有資料結構概念。然而在 document級,可以通過$unset

在update操作從文件中刪除列。

db.users.update(

{ },

{ $unset: { join_date: "" } },

{ multi: true }

)

CREATE INDEX idx_user_id_asc

ON users(user_id)

db.users.createIndex( { user_id: 1 } )

CREATE INDEX

idx_user_id_asc_age_desc

ON users(user_id, age DESC)

db.users.createIndex( { user_id: 1, age: -1 } )

DROP TABLE users

db.users.drop()

插入/刪除/更新 語句對比

SQL  Statements

MongoDB  Statements

INSERT INTO

users(user_id,

age

status)

VALUES ("bcd001",

45,

"A")

db.users.insert(

{ user_id: "bcd001", age:

45, status: "A" }

)

DELETE FROM users

WHERE status = "D"

db.users.remove( { status: "D" } )

DELETE FROM users

db.users.remove({})

UPDATE users

SET status = "C"

WHERE age > 25

db.users.update(

{ age: { $gt: 25 } },

{ $set: { status: "C" } },

{ multi: true }

)

UPDATE users

SET age = age + 3

WHERE status = "A"

db.users.update(

{ status: "A" } ,

{ $inc: { age: 3 } },

{ multi: true }

)

查詢類操作對比 

SQL SELECT Statements

MongoDB find() Statements

SELECT *

FROM users

db.users.find()

SELECT id,

user_id,

status

FROM users

db.users.find(

{ },

{ user_id: 1, status: 1, _id: 0 }

)

SELECT user_id, status

FROM users

db.users.find(

{ },

{ user_id: 1, status: 1 }

)

SELECT *

FROM users

WHERE status = "A"

db.users.find(

{ status: "A" }

)

SELECT user_id, status

FROM users

WHERE status = "A"

db.users.find(

{ status: "A" },

{ user_id: 1, status: 1, _id: 0 }

)