Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 部署 MongoDB 與常用操作全攻略

MongoDB 是一款流行的文件型資料庫,本文示範如何在 Linux 上完成安裝部署,並整理日常操作與權限設定。

一、安裝部署

1. 建立資料夾,例如 /opt/mongodb/single 與 /opt/mongodb/data/db。

2. 進入 single 目錄下載安裝包:

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-2.4.6.tgz

3. 解壓並修改目錄名稱:

mv mongodb-linux-x86_64-2.4.6 mongo

4. 進入 mongo 目錄並建立設定檔 conf/conf.properties:

port=27017
dbpath=/opt/mongotest/data/db
logpath=/opt/mongotest/single/mongo/log/mongo.log
logappend=true
fork=true

5. 啟動 mongo:

./bin/mongod -f conf/conf.properties

看到 child process started successfully 即代表背景啟動成功。

二、日常操作

連接:./mongo
查看資料庫:show dbs
查看目前所在庫:db
建立資料庫:use openfire(暫時性,不做操作離開後會被刪除)
刪除目前庫:db.dropDatabase()
查看使用者:show users
查看集合:show collections
建立集合:db.createCollection("mycollection")

建立集合並指定屬性:

db.createCollection("mycol", { capped: true, autoIndexID: true,
size: 6142800, max: 10000 })

其中 capped 表示啟用固定大小的封頂集合,size 為最大位元組數,max 為允許的最大文件數。另一種建立方式是插入資料時自動建立:

db.MySecondCollection.insert({"name": "ming"})

刪除集合:db.CollectionName.drop()

插入資料(須為 JSON 格式,否則會報語法錯誤):

db.MyFirstCollection.insert({"_id":"3","title":"mongotest","description":"this is test"})

_id 是 MongoDB 預設主鍵,會自動產生,也可手動指定;若插入重複 _id 會出現 duplicate key 錯誤。

查看記錄:db.MySecondCollection.findOne()
條件查詢:db.MySecondCollection.findOne({"name":"ming"})

更新記錄:

db.MyFirstCollection.update({"title":"mongotest"},
{$set:{"title":"new title"}}, true, false)

update 參數說明:criteria 為查詢條件,objNew 為更新物件,upsert 若為 true 則在找不到時插入,multi 若為 true 則更新所有符合條件的記錄。常用更新運算子包括 $inc(遞增)、$set(設值)、$unset(刪除欄位)、$push(追加陣列)、$rename(重新命名欄位)。

三、權限設定

先切換到 admin 庫 use admin,再新增使用者 db.addUser("root","admin")。注意必須先為 admin 庫建立使用者,否則後續進入具體庫時仍可能不受權限約束,因為 admin 使用者預設擁有最高權限。

為具體庫新增使用者:

use openfire
db.addUser("openfire","password")

重啟並啟用認證,可在啟動時加上 –auth 參數,或直接在設定檔加入 auth=true(推薦)。啟用後查詢會出現 not authorized 錯誤,需先認證:

db.auth("openfire","password")

也可在進入時直接帶上庫名與帳密:

./bin/mongo openfire -uopenfire -ppassword

四、進階技巧

find() 可指定回傳欄位以减少流量,語法為 db.collection.find(query, projection),其中 1 或 true 代表回傳、0 或 false 代表不回傳,_id 預設總是回傳,除非明確設為 0:

db.MyFirstCollection.findOne({"title":"new title"},{"description":1,"_id":0});
Copyright © Linux教程網 All Rights Reserved