mangodb介绍, 安装, 连接, 用户管理, 创建集合

Mangodb介绍

  • 官网www.mongodb.com, 当前最新版3.4
  • C++编写,基于分布式的,属于NoSQL的一种
  • 在NoSQL中是最像关系型数据库的 MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。
  • MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档、数组及文档数组。
  • 关于JSON http://www.w3school.com.cn/json/index.asp
    在这里插入图片描述
  • 因为基于分布式,所以很容易扩展

MongoDB和关系型数据库对比

在这里插入图片描述

  • 关系型数据库数据结构
    在这里插入图片描述

  • MongoDB数据结构
    在这里插入图片描述

Mongodb安装

  • epel自带的mongodb版本为2.6,我们需要安装3.4版本
  • 官方安装文档https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/
  • cd /etc/yum.repos.d/
  • vim mongodb-org-3.4.repo//加入如下内容
    [mongodb-org-3.4]
    name=MongoDB Repository
    baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.4/x86_64/
    gpgcheck=1
    enabled=1
    gpgkey=https://www.mongodb.org/static/pgp/server-3.4.asc
  • yum list |grep mongodb //可以看到mongodb相关的rpm包
  • yum install -y mongodb-org
  • 备用下载链接https://coding.net/u/aminglinux/p/yuanke_centos7/git/tree/master/21NOSQL/mongodb_rpm包

Mongodb连接

  • systemctl start mongod //启动服务
  • 在本机可以直接运行命令mongo进入到mongodb shell中
  • 如果mongodb监听端口并不是默认的27017,则在连接的时候需要加–port 选项,例如
    mongo --port 27018
  • 连接远程mongodb,需要加–host,例如
    mongo --host 127.0.0.1
  • 如果设置了验证,则在连接的时候需要带用户名和密码
    mongo -uusername -ppasswd --authenticationDatabase db //这个和MySQL挺像
[root@draft src]# mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
[root@draft src]# mongo --port 27017 --host 127.0.0.1   #都可进入mongo;
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 3.4.9
[root@draft src]# mongo --port 27017 --host 192.168.87.149  #使用其他IP登陆;
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
[root@draft src]# cat /etc/mongod.conf |grep 127
  bindIp: 127.0.0.1,192.168.87.149  #对应的配置文件修改;

MongoDB用户管理

  • use admin//需要切换到admin库
  • db.createUser( { user: “admin”, customData: {description: “superuser”}, pwd: “admin122”, roles: [ { role: “root”, db: “admin” } ] } )
  • user指定用户,customData为说明字段,可以省略,pwd为密码,roles指定用户的角色,db指定库名
  • use admin //切换到admin库
  • db.system.users.find() //列出所有用户,需要切换到admin库
  • show users //查看当前库下所有的用户
  • db.dropUser(‘admin’) //删除用户
  • 若要用户生效,还需要编辑启动脚本vim /usr/lib/systemd/system/mongod.service,在OPTIONS=后面增–auth
  • 重启服务systemctl restart mongod
  • mongo -u “admin” -p “admin122” --authenticationDatabase “admin”
> use admin     #用户帐号库;
switched to db admin
> show tables;
system.version
> db.createUser( { user: "admin", customData: {description: "superuser"}, pwd: "admin122", roles: [ { role: "root", db: "admin" } ] } )    #新建用户;
Successfully added user: {
	"user" : "admin",
	"customData" : {
		"description" : "superuser"
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}
> db.system.users.find()   #显示用户;
{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "Nwcuohnkryrplv3n4CLodg==", "storedKey" : "cdUHjRqolOJuj0yFrt0Px7s8Vlg=", "serverKey" : "aTyyUn1r7tu5JyCcqhvCZ5fKzDY=" } }, "customData" : { "description" : "superuser" }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
> show users    #显示用户;
{
	"_id" : "admin.admin",
	"user" : "admin",
	"db" : "admin",
	"customData" : {
		"description" : "superuser"
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}
> db.dropUser('admin')   #删除用户;
true
> db.createUser( { user: "admin", customData: {description: "superuser"}, pwd: "admin122", roles: [ { role: "root", db: "admin" } ] } ) 
Successfully added user: {
	"user" : "admin",
	"customData" : {
		"description" : "superuser"
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}
> exit
bye
[root@draft src]# vim /usr/lib/systemd/system/mongod.service   #修改配置使用密码登陆;
[root@draft src]# cat /usr/lib/systemd/system/mongod.service |grep Envir
Environment="OPTIONS=--auth -f /etc/mongod.conf"   #修改的句子;修改后不能像设置前无密码登陆(进去后,使用命令失败);
[root@draft src]# systemctl restart mongod
Warning: mongod.service changed on disk. Run 'systemctl daemon-reload' to reload units.
[root@draft src]# systemctl daemon-reload
[root@draft src]# systemctl restart mongod
[root@draft src]# mongo -u "admin" -p "admin122" --port 27017 --host 192.168.87.149 --authenticationDatabase "admin"
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
> show databases;
admin  0.000GB
local  0.000GB
> use local
switched to db local
> show tables;
startup_log
> use admin
switched to db admin
> show tables;
system.users
system.version
> show users
{
	"_id" : "admin.admin",
	"user" : "admin",
	"db" : "admin",
	"customData" : {
		"description" : "superuser"
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}
> 
  • use db1
  • db.createUser( { user: “test1”, pwd: “123aaa”, roles: [ { role: “readWrite”, db: “db1” }, {role: “read”, db: “db2” } ] } )
  • test1用户对db1库读写,对db2库只读。
  • 之所以先use db1,表示用户在 db1 库中创建,就一定要db1库验证身份,即用户的信息跟随随数据库。比如上述 test1虽然有 db2 库的读取权限,但是一定要先在db1库进行身份验证,直接访问会提示验证失败。
  • db.auth(“test1”, “123aaa”) 命令
[root@draft src]# mongo -u "admin" -p "admin122" --port 27017 --host 192.168.87.149 --authenticationDatabase "admin"
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
> use db1
switched to db db1   #在db1里新建用户;
> db.createUser( { user: "test1", pwd: "123aaa", roles: [ { role: "readWrite", db: "db1" }, {role: "read", db: "db2" } ] } )
Successfully added user: {
	"user" : "test1",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "db1"
		},
		{
			"role" : "read",
			"db" : "db2"
		}
	]
}
> exit
bye
[root@draft src]# mongo -u "test1" -p "123aaa" --port 27017 --host 192.168.87.149 --authenticationDatabase "db2"
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
2019-12-18T12:57:49.560+0800 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1461:20
@(auth):6:1
@(auth):1:2
exception: login failed   #db1新建的用户,不能直接登陆db2,即使有权限;
[root@draft src]# mongo -u "test1" -p "123aaa" --port 27017 --host 192.168.87.149 --authenticationDatabase "db1"  #可以登陆db2;
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
> use db2;
switched to db db2
> show tables;
> 
[root@draft src]# mongo -u "admin" -p "admin122" --port 27017 --host 192.168.87.149 --authenticationDatabase "admin"
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
> use db1
switched to db db1   #在db1为admin授权;
> db.createUser( { user: "admin", pwd: "admin122", roles: [ { role: "readWrite", db: "db1" } ] } )
Successfully added user: {
	"user" : "admin",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "db1"
		}
	]
}
> exit
bye
[root@draft src]# mongo -u "test1" -p "123aaa" --port 27017 --host 192.168.87.149 --authenticationDatabase "db1"
MongoDB shell version v3.4.9
connecting to: mongodb://192.168.87.149:27017/
MongoDB server version: 3.4.9
> use db1  
switched to db db1    
> db.auth("admin","admin122")    #admin授权后才可登陆db1,root权限也只用于admin库;
1
> db.auth("test1", "123aaa")    #转回去test1;
1
> use db2      #test1可登陆db2;
switched to db db2
> db.auth("admin","admin122")   #这时切换到admin帐号,提示失败,admin没有db2的权限;
Error: Authentication failed.
0

MongoDB用户角色

  • Read:允许用户读取指定数据库
  • readWrite:允许用户读写指定数据库
  • dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
  • userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
  • clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
  • readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
  • readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
  • userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
  • dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
  • root:只在admin数据库中可用。超级账号,超级权限

MongoDB创建集合

  • db.createCollection(“mycol”, { capped : true, size : 6142800, max : 10000 } ) //语法:db.createCollection(name,options)
  • name就是集合的名字,options可选,用来配置集合的参数,参数如下
  • capped true/false (可选)如果为true,则启用封顶集合。封顶集合是固定大小的集合,当它达到其最大大小,会自动覆盖最早的条目。如果指定true,则也需要指定尺寸参数。
  • autoindexID true/false (可选)如果为true,自动创建索引_id字段的默认值是false。
  • size (可选)指定最大大小字节封顶集合。如果封顶如果是 true,那么你还需要指定这个字段。单位B
  • max (可选)指定封顶集合允许在文件的最大数量。

MongoDB数据管理

  • show collections //查看集合,或者使用show tables
  • db.Account.insert({AccountID:1,UserName:“123”,password:“123456”}) //如果集合不存在,直接插入数据,则mongodb会自动创建集合
  • db.Account.update({AccountID:1},{"$set":{“Age”:20}}) //更新
  • db.Account.find() //查看所有文档
  • db.Account.find({AccountID:1}) //根据条件查询
  • db.Account.remove({AccountID:1}) //根据条件删除
  • db.Account.drop() //删除所有文档,即删除集合
  • use dbname //先进入对应的库
  • db.printCollectionStats() // 然后查看集合状态
> db.createCollection("mycol", { capped : true, size : 6142800, max : 10000 } )  #创建一个集合,指定一些参数;
{ "ok" : 1 }
> show tables;
mycol
> show collections;
mycol
> db.Account.insert({AccountID:1,UserName:"123",password:"123456"})   #创建集合并写入一个数据;
WriteResult({ "nInserted" : 1 })
> show tables;
Account
mycol
> db.Account.insert({AccountID:2,UserName:"llkskj",password:"lkki"})   #写入第二个数据;
WriteResult({ "nInserted" : 1 })
> db.Account.update({AccountID:1}, {"$set":{"Age":20}})     #修改,增加一个键值;
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.Account.find()      #显示所有行;
{ "_id" : ObjectId("5df9bca0e57e59eba1b0690f"), "AccountID" : 1, "UserName" : "123", "password" : "123456", "Age" : 20 }
{ "_id" : ObjectId("5df9bcbbe57e59eba1b06910"), "AccountID" : 2, "UserName" : "llkskj", "password" : "lkki" }
> db.Account.find({AccountID:2})   #筛选;
{ "_id" : ObjectId("5df9bcbbe57e59eba1b06910"), "AccountID" : 2, "UserName" : "llkskj", "password" : "lkki" }
> db.Account.remove({AccountID:1})    #删除一行;
WriteResult({ "nRemoved" : 1 })
> db.Account.find()
{ "_id" : ObjectId("5df9bcbbe57e59eba1b06910"), "AccountID" : 2, "UserName" : "llkskj", "password" : "lkki" }
> db.Account.drop()      #删除一个集合;
true
> show tables;
mycol
> db.printCollectionStats()   #显示集合信息;
mycol
{
	"ns" : "db1.mycol",
	"size" : 0,
	"count" : 0,
	"storageSize" : 4096,
	"capped" : true,      #指定的参数;
	"max" : 10000,
	"maxSize" : 6142976,

> db.Account.insert({AccountID:1,UserName:"123",password:"123456"})
WriteResult({ "nInserted" : 1 })
> db.printCollectionStats()
Account
{
	"ns" : "db1.Account",
	"size" : 80,
	"count" : 1,
	"avgObjSize" : 80,
	"storageSize" : 16384,
	"capped" : false,    #默认参数;
发布了125 篇原创文章 · 获赞 5 · 访问量 4615

猜你喜欢

转载自blog.csdn.net/tanyyinyu/article/details/103583051