天天看點

Mongodb初探

下載下傳

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.2.3.tg

解壓後修改名稱

tar xvzf mongodb-linux-x86_64-rhel62-3.2.3.tg

mv mongodb-linux-x86_64-rhel62-3.2.3.tg mongodb

mv mongodb /usr/local/

mkdir /data/db

./mongod

#啟動安全模式

#./mongod --auth >> mongodb.log & 

啟動shell

./mongo

簡單插入:

> db.test.insert({"name":"cctv","time":"1952"})

WriteResult({ "nInserted" : 1 })

查找

> db.test.find()

{ "_id" : ObjectId("56c812e8c3173d7c3942bf94"), "type" : "Fuck" }

{ "_id" : ObjectId("56c81e9a2b323f6d772f237b"), "name" : "cctv", "time" : "1952" }

更新 update方法的第一個參數為“查找的條件”,第二個參數為“更新的值”

>db.test.update({"name":"cctv"},{"name":"China-CNTV"})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

>

删除

remove中如果不帶參數将删除所有資料,呵呵,很危險的操作,在mongodb中是一個不可撤回的操作,三思而後行

> db.test.remove({"name":"China-CNTV"})

WriteResult({ "nRemoved" : 2 })

啟用認證

mongod 啟動預設沒有開啟權限,你需要指定 –auth 啟動,或者在配置檔案中設定security.authorization 為 “enabled”

建立使用者

db.createUser(user, writeConcern)

    文檔 http://docs.mongodb.org/manual/reference/method/db.createUser/#db.createUser

user格式

{ user: "<name>",

  pwd: "<cleartext password>",

  customData: { <any information> },

  roles: [

    { role: "<role>", db: "<database>" } | "<role>",

    ...

  ]

}

writeConcern:

例如 {w: “majority”, j: true, wtimeout: 5000}

    w選項:允許的值分别是 1、0、大于1的值、”majority”、;

    j選項:確定mongod執行個體寫資料到磁盤上的journal(日志),這可以確定mongd以外關閉不會丢失資料。設定true啟用。

    wtimeout:指定一個時間限制,以毫秒為機關。wtimeout隻适用于w值大于1。

Built-In Roles(内置角色):

    資料庫使用者角色:read、readWrite;

    資料庫管理角色:dbAdmin、dbOwner、userAdmin;

    叢集管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager;

    備份恢複角色:backup、restore;

    所有資料庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase

    超級使用者角色:root

    // 這裡還有幾個角色間接或直接提供了系統超級使用者的通路(dbOwner 、userAdmin、userAdminAnyDatabase)

    内部角色:__system

creatUser例子

建立超級管理者

use admin

db.createUser({

    user:"username",

    pwd:"password",

    roles:["root"]

})

在products資料庫建立accountAdmin01使用者,擁有readWrite權限,對admin資料庫擁有clusterAdmin跟readAnyDatabase權限

use products

db.createUser( { "user" : "accountAdmin01",

                 "pwd": "cleartext password",

                 "customData" : { employeeId: 12345 },

                 "roles" : [ { role: "clusterAdmin", db: "admin" },

                             { role: "readAnyDatabase", db: "admin" },

                             "readWrite"

                             ] },

               { w: "majority" , wtimeout: 5000 } )

登入

use collectionName

db.auth("username",'password")

檢視使用者

show users

删除使用者

db.dropUser("username")

更改使用者密碼

db.changeUserPassword("username","password")

更新使用者

建立或者切換資料庫

use dbname

切換到admin

      本文轉自flyingzf  51CTO部落格,原文連結:http://blog.51cto.com/flyingzf/1743678,如需轉載請自行聯系原作者