MongoDB配置與基本使用

mongoDB層次關係:      數據庫>集合>文檔sql

環境: Ubuntu14.04 MongoDB存儲路徑爲/opt/mongodb 下文用MPATH代替mongodb

1 安裝和啓動數據庫

1.1 下載MongoDB3.2.9最新版本vim

1.2 tar xf MONGODB.tar.gz數組

1.3 添加到環境變量 /etc/profilenosql

1.4 mongod -dbpath MPATH/data/dbcode

1.5 mongo 啓動mongoDB SHELL對象

 

2 配置管理員和用戶ip

2.1 查看當前數據庫[僅一個local] 切換到admin數據庫[準備建立用戶管理員]rem

show dbs

use admin

2.2 建立用戶管理員[管理用戶的賬號]

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

# 成功建立後有如下提示

Successfully added user: {
	"user" : "master",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}

2.3 配置mongoDB認證和外鏈[默認只有localhost能鏈接]

設置ip [先關閉mongod服務]

sudo vim /etc/mongod.conf

新建配置文件並修改輸入如下內容[容許外鏈]

bind_ip = 0.0.0.0  

2.4 開啓認證模式

mongod -f /etc/mongod.conf --auth --dbpath MPATH/data/db

auth: 認證模式

f: 配置文件 同--config

2.5 認證登錄mongoDB

mongo 

use dbs

ERROR # 沒有權限

use admin

db.auth("master", "123456")

1 # 表示成功

2.6 建立其餘用戶

db.createUser({user:"hakase",pwd:"123456",roles:[{role:"readWrite",db:"nosql"}]})

2.7 用其餘用戶登錄

use admin

db.auth("hakase","123456")

3 使用數據庫

3.1 建立數據庫/集合

使用兩個終端 實際上是三個 還有一個mongod ...

    一個登錄hakase來使用nosql數據庫

    一個登錄master來查看數據庫狀況

hakase:

use nosql

db.createCollection("test")

show collections

master:

show dbs

3.2 刪除數據庫

由於感受太麻煩 從新創建了一個超級超級用戶...

db.createUser(
  {user:"god",
  pwd:"123456",
  roles:["readWriteAnyDatabase","dbAdminAnyDatabase","clusterAdmin", "userAdminAnyDatabase"]}
)

 而後刪除數據庫nosql

use nosql

db.dropDatabase()

{ "dropped" : "nosql", "ok" : 1 } # 刪除成功 用 show dbs 命令看到nosql數據庫已不存在

3.3 複製數據庫

由於數據庫上一步刪掉了 因此還得從新建... 此次用了god賬號登錄

use nosql

db.createCollection("test")

db.createCollection("test2")

show dbs

show collections

接下來複制nosql數據庫爲copy_nosql

db.copyDatabase("nosql", "copy_nosql")

show dbs

3.4 管理集合 依然在nosql中

建立集合

db.createCollection("test3")

刪除集合

coll = db.getCollection("test3")

coll.drop()

show collections

在集合中插入文檔

coll = db.getCollection("test")

coll.insert({name:"ming", age:20})

coll.insert({name:"hong", age:18})

coll.find()

在集合中查找文檔

coll.find()

coll.find({name:"hong"})

在集合中刪除文檔

coll.remove({age:20})

coll.find()

在集合中更新/修改文檔

惟一一個比較複雜的

db.update(query, update, opts)

query 指定匹配查詢文檔

update 設置更新運算符

    $inc遞增

    $set設置字段的值

    $push 條目推送到數組

opts 有兩個屬性

upsert 若沒有找到則插入 理解:     if (!find()) insert else update

multi 查詢匹配的全部文檔都更新 不然只更新第一個找到的文檔

coll.update(
  {name:"hong"},
  {$set:{age:22}},
  {upsert:false, multi:true}
)

coll.find()

db.save(obj) 保存對象的更改 和update區別不大

可是要求要找_id 不然你怎麼肯定保存哪一個對象呢?

coll.save(
  {_id:ObjectId("57de3078bf66f6a50d3ff11d"),
  name:"gang",
  age:19}
)

coll.find()
相關文章
相關標籤/搜索