MongoDB 建立使用者,建立資料庫,刪除資料庫
阿新 • • 發佈:2020-12-07
文章目錄
建立使用者
mongo
use admin
db.createUser(
{
user: "lyh",
pwd: "123456",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
MongoDB 建立資料庫
語法
MongoDB 建立資料庫的語法格式如下:
use DATABASE_NAME
如果資料庫不存在,則建立資料庫,否則切換到指定資料庫。
> use dbtest switched to db dbtest > db dbtest >
你想檢視所有資料庫,可以使用 show dbs 命令:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
>
我們剛建立的資料庫 dbtest並不在資料庫的列表中, 要顯示它,我們需要向 dbtest資料庫插入一些資料。
> db.dbtest.insert({"name":"測試"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
dbtest 0.000GB
MongoDB 中預設的資料庫為 test,如果你沒有建立新的資料庫,集合將存放在 test 資料庫中。
注意: 在 MongoDB 中,集合只有在內容插入後才會建立! 就是說,建立集合(資料表)後要再插入一個文件(記錄),集合才會真正建立。
MongoDB 刪除資料庫
語法
MongoDB 刪除資料庫的語法格式如下:
db.dropDatabase()
刪除當前資料庫,預設為 test,你可以使用 db 命令檢視當前資料庫名。
例項
首先,檢視所有資料庫:
> show dbs
admin 0.000GB
config 0.000GB
dbtest 0.000GB
local 0.000GB
接下來我們切換到資料庫 runoob:
> use dbtest switched to db dbtest
執行刪除命令:
> db.dropDatabase()
{ "dropped" : "dbtest", "ok" : 1 }
最後,我們再通過 show dbs 命令資料庫是否刪除成功:
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB