简介:

Mongodb 是一个由 C++ 语言编写的基于分布式文件存储的数据库,是目前最像关系型数据库的非关系型数据库。

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

一、直接安装吧,CentOS 6.8 x86_64

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

shell > mv mongodb-linux-x86_64-rhel62-3.6. /usr/local/mongodb

# 设置环境变量,export PATH=$PATH:/usr/local/mongodb/bin && source /etc/profile

二、启动、客户端连接

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

# 创建一个数据目录跟日志目录

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:
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.
Welcome to the MongoDB shell.
For interactive help, type "help".

# 连接本机 mongodb,--bind_ip 指定要监听的地址,--help 查看帮助信息

三、基本操作

> 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 : } ) list objects in foo where a ==
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 显示帮助信息

1、数据库、数据表

# 都是不需要事先创建的

> db
test
> show dbs
admin .000GB
config .000GB
local .000GB

# 默认连接到了 test 库,目前这台 mongo 中有三个数据库:admin、config、local

2、切换数据库,直接插入数据

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

# 数据库中没有数据,是不会显示的 ( 还没有正式生成数据文件 )

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

# 成功插入一条数据

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

# 更新数据成功

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

# 删除所有 Age = 28 的数据

四、权限验证

# 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 数据库中使用,全局权限最高)

1、创建用户、分配角色

> 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:
child process started successfully, parent exiting

2、用户身份认证、权限验证

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

# 重新连接后,输入 show dbs 报错,提示认证失败

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

# 用户认证后,再次执行则不报错

> use spider_db
switched to db spider_db
> db.tmdb.insert({"id": , "name": "wang"})
WriteResult({
"writeError" : {
"code" : ,
"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")

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

# 我们在 spider_db 数据库中切换了用户 user02,成功创建了一条记录,也可以读到该记录,并且也显示出了集合(表)、跟数据库

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

# 我们在 spider_db 数据库中切换用户 user01 时,提示认证失败,当切换到 admin 数据库中再次切换用户时,成功了。

# 这是我用 user01 这个只读用户插入数据居然成功了!!!然后我退出客户端,重新登录认证后,还是用这个 user01 只读用户创建数据提示失败。

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

# 可见,这个切换用户是不是有点问题呢 ???

3、查看当前所有用户

> use admin
switched to db admin
> db.auth("dba", "dba") > db.system.users.find().pretty()
{
"_id" : "admin.dba",
"user" : "dba",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : ,
"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" : ,
"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" : ,
"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" : ,
"salt" : "Mem9nRSILHK7ZWQBIqP9yA==",
"storedKey" : "o8uGPAL4aNIFNT1Y2MWyST8NUe8=",
"serverKey" : "TWo+f+QmO0AqGg1L83tku/hpM+Y="
}
},
"roles" : [
{
"role" : "read",
"db" : "spider_db"
}
]
}

# 对 就是这样

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

# 统计咯

Mongodb 折腾笔记的更多相关文章

  1. MongoDB学习笔记系列

    回到占占推荐博客索引 该来的总会来的,Ef,Redis,MVC甚至Sqlserver都有了自己的系列,MongoDB没有理由不去整理一下,这个系列都是平时在项目开发时总结出来的,希望可以为各位一些帮助 ...

  2. PHP操作MongoDB学习笔记

    <?php/*** PHP操作MongoDB学习笔记*///*************************//**   连接MongoDB数据库  **////*************** ...

  3. MongoDB 学习笔记(原创)

    MongoDB 学习笔记 mongodb 数据库 nosql 一.数据库的基本概念及操作 SQL术语/概念 MongoDB术语/概念 解释/说明 database database 数据库 table ...

  4. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

  5. MongoDB学习笔记(转)

    MongoDB学习笔记(一) MongoDB介绍及安装MongoDB学习笔记(二) 通过samus驱动实现基本数据操作MongoDB学习笔记(三) 在MVC模式下通过Jqgrid表格操作MongoDB ...

  6. 【转】MongoDB学习笔记(查询)

    原文地址 MongoDB学习笔记(查询) 基本查询: 构造查询数据. > db.test.findOne() { "_id" : ObjectId("4fd58ec ...

  7. MongoDB学习笔记(六)--复制集+sharding分片 && 总结

    复制集+sharding分片                                                               背景 主机 IP 服务及端口 Server A ...

  8. MongoDB学习笔记(五)--复制集 && sharding分片

    主从复制                                                                                       主从节点开启 主节 ...

  9. MongoDB学习笔记(四)--索引 && 性能优化

    索引                                                                                             基础索引 ...

随机推荐

  1. hadoop 安装、命令

    hadoop安装步骤: 安装java 安装hadoop 下载地址:http://apache.claz.org/hadoop/common/ (说明:该网址current文件夹下,是最新版) hado ...

  2. PHP安全相关的配置(1)

    PHP作为一门强大的脚本语言被越来越多的web应用程序采用,不规范的php安全配置可能会带来敏感信息泄漏.SQL注射.远程包含等问题,规范的安全配置可保障最基本的安全环境.下面我们分析几个会引发安全问 ...

  3. tyvj1035棋盘覆盖——二分图匹配

    题目:http://www.joyoi.cn/problem/tyvj-1035 把可放的位置作为节点,相邻的连边. 可用天然有的编号作为节点的编号. 果然只用连单向边就行了.也只需记录另一部的对应点 ...

  4. import和export语法报错

    “最近在学习ES6”,但是在chrome中新建了js通过ES6语法(import,export)无法引入外部JS,报错: Uncaught SyntaxError:Unexpected token { ...

  5. NoSQL非结构化数据库高级培训课程-大纲

    一.课程概述 本课程面向No-SQL开发人员.系统分析和系统架构师,目的在于帮助他们建立起完整的No-SQL数据库的概念,应用场景.相关开源技术框架和优缺点. 二.课程大纲 主题 时间 主题 No-S ...

  6. ubuntu 14.04 git clone 出现 fatal: Unable to find remote helper for 'https'

    当你编译安装git时因为没有安装(lib)curl-devel所以导致git clone 和 git push 都会出现这个错误 如果你安装了(lib)curl-devel,然后重新编译安装git就没 ...

  7. js中一些对字符串的操作等

    看代码时候,发现一些写的很好的js对字符串的操作,记录下来,持续更新等>... js trim()的实现: function trim(string){ return string.replac ...

  8. python-appium520-2初步使用

    1.录制自动化脚本 场景:启动雪球,点击我的,登陆雪球,选择手机及其他登陆,输入手机号 2.Appium客户端 客户端介绍:https://github.com/appium/appium/blob/ ...

  9. 深度优先搜索DFS(二)

    总结下图里面的常用模板: DFS(u){ vis[u]=true; for(从u出发能到达的所有顶点v){ if(vis[v]==false){ DFS(v); } } } DFSTrave(G){ ...

  10. MapReduce C++ Library

    MapReduce C++ Library for single-machine, multicore applications Distributed and scalable computing ...