Mongodb 折騰筆記


簡介:linux

Mongodb 是一個由 C++ 語言編寫的基於分佈式文件存儲的數據庫,是目前最像關係型數據庫的非關係型數據庫。mongodb

下載地址:https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.6.3.tgz

1、直接安裝吧,CentOS 6.8 x86_64shell

shell > tar zxf mongodb-linux-x86_64-rhel62-3.6.3.tgz

shell > mv mongodb-linux-x86_64-rhel62-3.6.3 /usr/local/mongodb

# 設置環境變量,export PATH=$PATH:/usr/local/mongodb/bin && source /etc/profile數據庫

2、啓動、客戶端鏈接分佈式

shell > mkdir -p /data/{mongo_data,logs}

# 建立一個數據目錄跟日誌目錄ide

shell > mongod --dbpath /data/mongo_data --logpath /data/logs/mongo.log --fork
about to fork child process, waiting until server is ready for connections.
forked process: 8659
child process started successfully, parent exiting

# --fork 後臺啓動 mongod 進程,--dbpath、--logpath 分別指定數據目錄跟日誌文件函數

shell > mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Welcome to the MongoDB shell.
For interactive help, type "help".

# 鏈接本機 mongodb,--bind_ip 指定要監聽的地址,--help 查看幫助信息ui

3、基本操做lua

> help
    db.help()                    help on db methods
    db.mycoll.help()             help on collection methods
    sh.help()                    sharding helpers
    rs.help()                    replica set helpers
    help admin                   administrative help
    help connect                 connecting to a db help
    help keys                    key shortcuts
    help misc                    misc things to know
    help mr                      mapreduce

    show dbs                     show database names
    show collections             show collections in current database
    show users                   show users in current database
    show profile                 show most recent system.profile entries with time >= 1ms
    show logs                    show the accessible logger names
    show log [name]              prints out the last segment of log in memory, 'global' is default
    use <db_name>                set current database
    db.foo.find()                list objects in collection foo
    db.foo.find( { a : 1 } )     list objects in foo where a == 1
    it                           result of the last line evaluated; use to further iterate
    DBQuery.shellBatchSize = x   set default number of items to display on shell
    exit                         quit the mongo shell

# 輸入 help 顯示幫助信息spa

一、數據庫、數據表

# 都是不須要事先建立的

> db
test
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

# 默認鏈接到了 test 庫,目前這臺 mongo 中有三個數據庫:admin、config、local

二、切換數據庫,直接插入數據

> use spider_db
switched to db spider_db
> db
spider_db
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

# 數據庫中沒有數據,是不會顯示的 ( 尚未正式生成數據文件 )

> db.spider_resource.insert({"id": 1, "name": "wang", "age": 28})
WriteResult({ "nInserted" : 1 })
> db.spider_resource.find()
{ "_id" : ObjectId("5ab0ba99090d8464fa486775"), "id" : 1, "name" : "wang", "age" : 28 }

# 成功插入一條數據

> db.spider_resource.update({"name": "wang"}, {$set: {"QQ": "25152069"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.spider_resource.find({"id": 1})
{ "_id" : ObjectId("5ab0ba99090d8464fa486775"), "id" : 1, "name" : "wang", "age" : 28, "QQ" : "25152069" }

# 更新數據成功

> db.spider_resource.deleteMany({"age": 28})
{ "acknowledged" : true, "deletedCount" : 1 }

# 刪除全部 Age = 28 的數據

4、權限驗證

# Mongodb 的權限驗證跟其他的數據庫,例如: MySQL、Redis 等都不一樣,不是統一權限驗證,而是基於數據庫的權限驗證。

# 例如,當你在 A 庫建立用戶後,你只能在 A 庫驗證,即便你建立用戶時給該用戶分配的數據庫不是 A 庫。

# MongoDB 內置角色:

>、數據庫用戶角色:read(對指定數據庫只讀)、readWrite(對指定數據庫讀寫)
>、數據庫管理角色:dbAdmin(對指定數據庫執行管理函數)、dbOwner(對指定數據庫有全部權)、userAdmin(對指定數據庫具備用戶管理權限)
>、集羣管理角色:clusterAdmin、clusterManager、clusterMonitor、hostManager

# 只容許在 admin 數據庫中使用,授予用戶對集羣的管理權限

>、備份恢復角色:backup、restore
>、全部數據庫角色:readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase

# 只容許在 admin 數據庫中使用,授予用戶對全部數據庫相應的權限

>、超級用戶角色:root(只容許在 admin 數據庫中使用,全局權限最高)

一、建立用戶、分配角色

> use admin
switched to db admin
> db.createUser({user: "dba", pwd: "dba", roles: [{role: "userAdminAnyDatabase", db: "admin"}]})
Successfully added user: {
    "user" : "dba",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}

# 切換到 admin 數據庫,建立了一個具備管理全部數據庫用戶的角色用戶

# 執行 db.shutdownServer() 關閉 mongodb 後,以驗證方式從新啓動。

shell > mongod --dbpath /data/mongo_data --logpath /data/logs/mongo.log --fork --auth
about to fork child process, waiting until server is ready for connections.
forked process: 15886
child process started successfully, parent exiting

二、用戶身份認證、權限驗證

> show dbs
2018-03-20T05:15:23.327-0400 E QUERY    [thread1] Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, $db: \"admin\" }",
    "code" : 13,
    "codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1
shellHelper.show@src/mongo/shell/utils.js:816:19
shellHelper@src/mongo/shell/utils.js:706:15
@(shellhelp2):1:1

# 從新鏈接後,輸入 show dbs 報錯,提示認證失敗

> use admin
switched to db admin
> db.auth("dba", "dba")
1
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

# 用戶認證後,再次執行則不報錯

> use spider_db
switched to db spider_db
> db.tmdb.insert({"id": 1, "name": "wang"})
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on spider_db to execute command { insert: \"tmdb\", ordered: true, $db: \"spider_db\" }"
    }
})

# 切換到 spider_db 數據庫,插入數據的時候報錯,提示認證失敗,先前建立的 userAdminAnyDatabase 角色用戶只有用戶管理權限

> use admin
switched to db admin
> db.createUser({user: "user01", pwd: "user01", roles: [{role: "read", db: "spider_db"}]})
Successfully added user: {
    "user" : "user01",
    "roles" : [
        {
            "role" : "read",
            "db" : "spider_db"
        }
    ]
}
> use spider_db
switched to db spider_db
> db.createUser({user: "user02", pwd: "user02", roles: [{role: "readWrite", db: "spider_db"}]})
Successfully added user: {
    "user" : "user02",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "spider_db"
        }
    ]
}

# 咱們在 admin 數據庫中建立了一個只讀用戶 user01,在 spider_db 數據庫中建立了一個讀寫用戶 user02。

> db.auth("user02", "user02")
1
> db.tmdb.insert({"id": 1, "name": "wang"})
WriteResult({ "nInserted" : 1 })
> db.tmdb.find()
{ "_id" : ObjectId("5ab0d35d0c6513083da7387c"), "id" : 1, "name" : "wang" }
> show collections
tmdb
> show dbs
admin      0.000GB
config     0.000GB
local      0.000GB
spider_db  0.000GB

# 咱們在 spider_db 數據庫中切換了用戶 user02,成功建立了一條記錄,也能夠讀到該記錄,而且也顯示出了集合(表)、跟數據庫

> db.auth("user01", "user01")
Error: Authentication failed.
0
> use admin
switched to db admin
> db.auth("user01", "user01")
1
> use spider_db
switched to db spider_db
> db.tmdb.find()
{ "_id" : ObjectId("5ab0d35d0c6513083da7387c"), "id" : 1, "name" : "wang" }

# 咱們在 spider_db 數據庫中切換用戶 user01 時,提示認證失敗,當切換到 admin 數據庫中再次切換用戶時,成功了。

# 這是我用 user01 這個只讀用戶插入數據竟然成功了!!!而後我退出客戶端,從新登陸認證後,仍是用這個 user01 只讀用戶建立數據提示失敗。

> use admin
switched to db admin
> db.auth("user01", "user01")
1
> use spider_db
switched to db spider_db
> db.tmdb.find()
{ "_id" : ObjectId("5ab0d35d0c6513083da7387c"), "id" : 1, "name" : "wang" }
{ "_id" : ObjectId("5ab0d5300c6513083da7387d"), "id" : 2, "name" : "xiao" }
{ "_id" : ObjectId("5ab0e1e6e1f734cf6e1f6373"), "id" : 3, "name" : "qiang" }
{ "_id" : ObjectId("5ab0e259e1f734cf6e1f6374"), "id" : 4, "name" : "king" }
> db.tmdb.insert({"id": 5, "name": "baby"})
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on spider_db to execute command { insert: \"tmdb\", ordered: true, $db: \"spider_db\" }"
    }
})

# 可見,這個切換用戶是否是有點問題呢 ???

三、查看當前全部用戶

> use admin
switched to db admin
> db.auth("dba", "dba")
1
> db.system.users.find().pretty()
{
    "_id" : "admin.dba",
    "user" : "dba",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "xZe7OF09184eRzmIrYah4A==",
            "storedKey" : "BW+tDxhWucq8OtgsndNIkTIg3go=",
            "serverKey" : "zWd0pqb1fyRlNdknJlOBjzfgf/k="
        }
    },
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        }
    ]
}
{
    "_id" : "admin.user01",
    "user" : "user01",
    "db" : "admin",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "gBT2977goyNF5lYTJrufxw==",
            "storedKey" : "UuuMWuQUEi5GgxAYHbwAxBDjbGY=",
            "serverKey" : "Lv79GMQSgNGqRR8R4LNzgCOWcd0="
        }
    },
    "roles" : [
        {
            "role" : "read",
            "db" : "spider_db"
        }
    ]
}
{
    "_id" : "spider_db.user02",
    "user" : "user02",
    "db" : "spider_db",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "UxsTe1hRECOvCqL4f4uB8A==",
            "storedKey" : "kf/SHhtTzSZzQDjHwszrR2wHu/c=",
            "serverKey" : "rXC9p41rGwyo9QyhkZWY1gTliAc="
        }
    },
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "spider_db"
        }
    ]
}
{
    "_id" : "spider_db.user03",
    "user" : "user03",
    "db" : "spider_db",
    "credentials" : {
        "SCRAM-SHA-1" : {
            "iterationCount" : 10000,
            "salt" : "Mem9nRSILHK7ZWQBIqP9yA==",
            "storedKey" : "o8uGPAL4aNIFNT1Y2MWyST8NUe8=",
            "serverKey" : "TWo+f+QmO0AqGg1L83tku/hpM+Y="
        }
    },
    "roles" : [
        {
            "role" : "read",
            "db" : "spider_db"
        }
    ]
}

# 對 就是這樣

> db.system.users.find().count()
4

# 統計咯

相關文章
相關標籤/搜索