Home | 簡體中文 | 繁體中文 | 雜文 | 打賞(Donations) | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 知乎專欄 | Search | Email

2.2. MongoDB 管理

2.2.1. Security and Authentication

開啟認證

# vim /etc/mongodb.conf
auth = true
		

重載配置檔案

# /etc/init.d/mongod reload
Stopping mongod:                                           [  OK  ]
Starting mongod:                                           [  OK  ]
		

2.2.1.1. 超級管理員

Database Administration Roles
			
use admin;
db.createUser(
   {
     user: "admin",
     pwd: "WkAFdmfVQpP1oAEkz4YVlMCDxkG36TAi",
     roles: [ "dbAdmin", "dbOwner", "userAdmin" ]
   }
);
			
			

2.2.1.2. 資料庫訪問用戶

注意,只有創建了超級管理後,下面的操作才會生效

MongoDB

			
use products
db.createUser(
   {
     user: "accountUser",
     pwd: "password",
     roles: [ "readWrite", "dbAdmin" ]
   }
)
			
			

早期版本

			
> use neo
switched to db neo
> db.addUser('neo','chen')
{
        "user" : "neo",
        "readOnly" : false,
        "pwd" : "68ace374737253d87e0ec91d4fcb673d"
}

> db.system.users.find()
{ "_id" : ObjectId("4c481404b9db6474d2fcb76f"), "user" : "neo", "readOnly" : false, "pwd" : "68ace374737253d87e0ec91d4fcb673d" }

> db.auth('neo','chen')
1
			
			

2.2.1.3. 資料庫監控用戶

			
db.createUser(
   {
     user: "monitor",
     pwd: "netkiller",
     roles: [ "clusterMonitor"]
   }
)			
			
			

2.2.1.4. 刪除用戶

Deleting Users 刪除用戶

To delete a user:

			
> db.getUsers();
[
	{
		"_id" : "test.monitor",
		"user" : "monitor",
		"db" : "test",
		"roles" : [
			{
				"role" : "dbOwner",
				"db" : "test"
			}
		]
	}
]
			
> db.dropUser('monitor')
ture

> db.getUsers();
[ ]
						
			

早期版本

			
db.system.users.remove( { user: username } )
			
			

2.2.1.5. 更新角色

			

db.updateUser( "monitor",
   {
     roles: [ "read", "clusterMonitor" ]
   }
)
			
			

2.2.2. Unique Indexes

增加索引:1(ascending),-1(descending)

2.2.2.1. 索引管理

增加索引

db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
		

索引子對象

		
db.logging.users.ensureIndex({address.city:1})
		
		

查看索引信息

db.logging.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "logging.logging",
		"name" : "_id_"
	}
]
		

db.logging.users.getIndexKeys()

[ { "_id" : 1 }, { "name" : 1 } ]
		

根據索引名刪除索引

		
> db.logging.users.dropIndex('name_1')
{ "nIndexesWas" : 2, "ok" : 1 }

> db.logging.users.getIndexKeys()
[ { "_id" : 1 } ]
		
		
2.2.2.1.1. 唯一索引
db.members.createIndex( { "user_id": 1 }, { unique: true } )
			
			
> db.apple.createIndex({"devicetoken":1},{unique: true})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}