MongoDB基础(三)—基本操作及管理

第1章 MongoDB的基本操作

1.1 查询帮助信息

> 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 : 1 } )     list objects in foo where a == 1
    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
# 或 KEYWORDS.help()
# 或 KEYWORDS.[TAB]
  • 说明:
  1. db:和数据库管理操作有关的
  2. rs:和replication set 复制集有关的命令
  3. sh:和shard分片有关的命令

1.2 常用操作

1.2.1 查看当前db版本

> db.version()
3.2.8

1.2.2 显示当前数据库

> db
test
# 或
> db.getName()
test

1.2.3 查询所有数据库

> show dbs
local  0.000GB
> show databases
local  0.000GB

1.2.4 切换到admin数据库

> use admin
switched to db admin

1.2.5 显示当前数据库状态

> db.stats()
{
    "db" : "admin",
    "collections" : 0,
    "objects" : 0,
    "avgObjSize" : 0,
    "dataSize" : 0,
    "storageSize" : 0,
    "numExtents" : 0,
    "indexes" : 0,
    "indexSize" : 0,
    "fileSize" : 0,
    "ok" : 1
}

1.2.6 查看当前数据库的连接机器地址

> db.getMongo()
connection to 127.0.0.1

1.3 数据库操作

1.3.1 指定数据库进行连接(默认连接本机test数据库):

[mongod@db01 ~]$ mongo 127.0.0.1/admin
MongoDB shell version: 3.2.8
connecting to: 127.0.0.1/admin
> db
admin

1.3.2 创建数据库

提示:当use的时候,系统就会自动创建一个数据库;如果use之后没有创建任何集合,系统就会删除这个数据库。

1.3.3 删除数据库

提示:如果没有选择任何数据库,会删除默认的test数据库。
> use test
switched to db test
> db.dropDatabase()
{ "ok" : 1 }

1.4 集合操作

1.4.1 创建集合

1.4.1.1 直接创建集合:

> db.createCollection('a')
{ "ok" : 1 }
> db.createCollection('b')
{ "ok" : 1 }

1.4.1.2 当插入一个文档的时候,一个集合就会自动创建:

> db.c.insert({username:"mongodb"})
WriteResult({ "nInserted" : 1 })

1.4.2 查看当前数据下的所有集合

> show collections
a
b
c
# 或
> db.getCollectionNames()
[ "a", "b", "c" ]
# 或
> show tables
a
b
c

1.4.3 查看集合内容

> db.c.find()
{ "_id" : ObjectId("5a1e4905dbb63d0ef5fe1f0e"), "username" : "mongodb" }
> db.a.find().pretty()      # 以格式化的方式显示信息
{
    "_id" : ObjectId("5a1e60e5dbb63d0ef5fe1f74"),
    "uid" : 1,
    "name" : "mongodb",
    "age" : 6,
    "date" : ISODate("2017-11-29T07:25:25.813Z")
}
{
    "_id" : ObjectId("5a1e60e5dbb63d0ef5fe1f75"),
    "uid" : 2,
    "name" : "mongodb",
    "age" : 6,
    "date" : ISODate("2017-11-29T07:25:25.813Z")
}

1.4.4 重命名集合

> db.a.renameCollection("a1")
{ "ok" : 1 }
> show collections
a1
b
c

1.4.5 删除集合

> use app
switched to db app
> db.a1.drop()
true
> show collections
b
c

1.5 数据操作

1.5.1 插入数据

> for(i=0;i<100;i++){db.a.insert({"uid":i,"name":"mongodb","age":6,"date":new Date()});}
WriteResult({ "nInserted" : 1 })

1.5.2 查询集合中的记录数

1.5.2.1 查询所有记录:

> db.a.find()
{ "_id" : ObjectId("5a1e4cd0dbb63d0ef5fe1f0f"), "uid" : 0, "name" : "mongodb", "age" : 6, "date" : ISODate("2017-11-29T05:59:44.245Z") }
...省略部分输出内容...
提示:默认每页显示20条记录,当显示不下的的情况下,可以用it迭代命令查询下一页数据。
  • 设置每页显示数据的大小:
> DBQuery.shellBatchSize=50     # 设置每页显示50条记录
50

1.5.2.2 查询第一条记录:

> db.a.findOne()
{
    "_id" : ObjectId("5a1e4cd0dbb63d0ef5fe1f0f"),
    "uid" : 0,
    "name" : "mongodb",
    "age" : 6,
    "date" : ISODate("2017-11-29T05:59:44.245Z")
}

1.5.2.3 查询指定记录

> db.a.find({uid:50})
{ "_id" : ObjectId("5a1e60e5dbb63d0ef5fe1fa5"), "uid" : 50, "name" : "mongodb", "age" : 6, "date" : ISODate("2017-11-29T07:25:25.843Z") }

1.5.2.4 查询总的记录数:

> db.a.count()
100

1.5.3 删除集合中的记录数

1.5.3.1 删除指定记录

> db.a.remove({uid:0})
WriteResult({ "nRemoved" : 1 })
> db.a.findOne()
{
    "_id" : ObjectId("5a1e60e5dbb63d0ef5fe1f74"),
    "uid" : 1,
    "name" : "mongodb",
    "age" : 6,
    "date" : ISODate("2017-11-29T07:25:25.813Z")
}

1.5.3.2 删除全部记录

> db.a.remove({})
WriteResult({ "nRemoved" : 100 })
> db.a.count()
0

1.6 查看集合存储信息

1.6.1 查看集合存储信息

> db.a.stats()
{
    "ns" : "app.a",
    "count" : 0,
    "size" : 0,
    "storageSize" : 20480,
    "capped" : false,
    "wiredTiger" : {
...省略部分输出内容...

1.6.2 查看集合中数据的原始大小

> db.a.dataSize()
0

1.6.3 查看集合中索引数据的原始大小

> db.a.totalIndexSize()
20480

1.6.4 查看集合中索引+数据压缩存储之后的大小

> db.a.totalSize()
40960

1.6.5 查看集合中数据压缩存储的大小

> db.a.storageSize()
20480

第2章 使用客户端工具

NoSQL Manager for MongoDB是一款类似于SQL Server Management Studio的数据库管理软件。

下载地址:https://www.mongodbmanager.com/

图片[1]|MongoDB基础(三)—基本操作及管理|leon的博客

第3章 用户管理

MongoDB数据库默认是没有用户名及密码的,即无权限访问限制,为了方便数据库的管理和安全,需要创建数据库用户。

3.1 创建用户

3.1.1 用户创建语法

{
    user: "<name>",
    pwd: "<cleartext password>",
    customData: { <any information> },
    roles: [
    { role: "<role>",
        db: "<database>" } | "<role>",
        ...
    ]
}
  • 语法说明:
  1. user字段:用户的名字
  2. pwd字段:用户的密码
  3. cusomData字段:为任意内容,例如可以为用户全名介绍
  4. roles字段:指定用户的角色,可以用一个空数组给新用户设定空角色;roles 字段可以指定内置角色和用户定义的角色。
提示:常用角色说明见官方文档:https://docs.mongodb.com/manual/reference/built-in-roles/

3.1.2 创建超级管理员(管理所有数据库)

> use admin
switched to db admin
> db.createUser(
  {
    user: "root",
    pwd: "root",
    roles: [ { role: "root", db: "admin" } ]
  }
)
Successfully added user: {
    "user" : "root",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

3.1.3 验证用户

> db.auth("root","root")
1

3.1.4 登录用户

[mongod@db01 ~]$ mongo -uroot -proot admin
MongoDB shell version: 3.2.8
connecting to: admin
Server has startup warnings:
> show tables
system.users
system.version
提示:如果不加用户名和密码及数据库名虽然也可以登录进数据库,但是无法访问其中的数据。
[mongod@db01 ~]$ mongo admin    # 不加用户名和密码无法访问数据
MongoDB shell version: 3.2.8
connecting to: admin
> show tables
2017-11-29T16:16:03.347+0800 E QUERY    [thread1] Error: listCollections failed: {
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listCollections: 1.0, filter: {} }",
    "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
shellHelper.show@src/mongo/shell/utils.js:754:9
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1

3.2 按生产需求创建应用用户

3.2.1 创建对某库的只读用户

[mongod@db01 ~]$ mongo -uroot -proot admin
> use test
switched to db test
> db.createUser(
  {
    user: "read",
    pwd: "read",
    roles: [ { role: "read", db: "test" } ]
  }
)
Successfully added user: {
    "user" : "read",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
> db.auth("read","read")
1

# 重新登录测试结果
[mongod@db01 ~]$ mongo -uread -pread test   # 以只读用户登录
> show tables                               # 进行查询操作(允许)
a
> db.a.insert({"uid":1,"name":"mongodb","age":6,"date":new Date()}) # 进行写入操作(报错)
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on test to execute command { insert: \"a\", documents: [ { _id: ObjectId('5a1e6ea7c550bef10cd42385'), uid: 1.0, name: \"mongodb\", age: 6.0, date: new Date(1511943847864) } ], ordered: true }"
    }
})

3.2.2 创建某库的读写用户

[mongod@db01 ~]$ mongo -uroot -proot admin
> use test
switched to db test
> db.createUser(
  {
    user: "readwrite",
    pwd: "readwrite",
    roles: [ { role: "readWrite", db: "test" } ]
  }
)
Successfully added user: {
    "user" : "readwrite",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ]
}
> db.auth("readwrite","readwrite")
1

# 重新登录测试结果
[mongod@db01 ~]$ mongo -ureadwrite -preadwrite test     # 以读写用户登录
> show tables                                           # 进行查询操作(允许)
a
> db.a.insert({"uid":1,"name":"mongodb","age":6,"date":new Date()}) # 进行写入操作(允许)
WriteResult({ "nInserted" : 1 })

3.2.3 分别对多库的不同权限的用户

[mongod@db01 ~]$ mongo -uroot -proot admin
> use test
switched to db test
> db.createUser(
{
    user: "roles",
    pwd: "roles",
    roles: [{ role: "readWrite",db: "test"},
        { role: "read", db: "app" }
    ]
}
)
Successfully added user: {
    "user" : "roles",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        },
        {
            "role" : "read",
            "db" : "app"
        }
    ]
}

3.2.4 角色分类

3.2.4.1 数据库用户角色(Database User Roles)

read:授予User只读数据的权限
readWrite:授予User读写数据的权限

3.2.4.2 数据库管理角色(Database Administration Roles)

dbAdmin:在当前dB中执行管理操作
dbOwner:在当前DB中执行任意操作
userAdmin:在当前DB中管理User

3.2.4.3 备份和还原角色(Backup and Restoration Roles)

backup
restore

3.2.4.4 跨库角色(All-Database Roles)

readAnyDatabase:授予在所有数据库上读取数据的权限
readWriteAnyDatabase:授予在所有数据库上读写数据的权限
userAdminAnyDatabase:授予在所有数据库上管理User的权限
dbAdminAnyDatabase:授予管理所有数据库的权限

3.2.4.5 集群管理角色(Cluster Administration Roles)

clusterAdmin:授予管理集群的最高权限
clusterManager:授予管理和监控集群的权限,A user with this role can access the config and local databases, which are used in sharding and replication, respectively.
clusterMonitor:授予监控集群的权限,对监控工具具有readonly的权限
hostManager:管理Server

3.3 查看用户

3.3.1.1 查看所有用户

> use admin
switched to db admin
> db.system.users.find();
{ "_id" : "admin.root", "user" : "root", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "6i+6c//UG92hsGAKE+Va8Q==", "storedKey" : "Qbq83Dx36ZVKiEYY/rTKU3r9e/M=", "serverKey" : "Wd3krHtSvNDqf52yl5ThiJnPbis=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
{ "_id" : "test.read", "user" : "read", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "7Krbf82gklo9PPJP9PivIg==", "storedKey" : "LEJWdJfREYuaKij9JdLSAeNoaXY=", "serverKey" : "tqYpPiMlz6f0q7Nwcu7z2K6O/Mo=" } }, "roles" : [ { "role" : "read", "db" : "test" } ] }
{ "_id" : "test.readwrite", "user" : "readwrite", "db" : "test", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "wj/mcQpF3szWftC5czfBnw==", "storedKey" : "gGJrtVSKWi6erHMUKpAghKjH7D0=", "serverKey" : "y8iWeEHmVGMwU+5VU0JEF9AIp/M=" } }, "roles" : [ { "role" : "readWrite", "db" : "test" } ] }

3.3.1.2 查看某个库中的用户

> use test
switched to db test
> show users
{
    "_id" : "test.read",
    "user" : "read",
    "db" : "test",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
{
    "_id" : "test.readwrite",
    "user" : "readwrite",
    "db" : "test",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ]
}

3.4 删除用户

[mongod@db01 ~]$ mongo -uroot -proot admin
> show users
{
    "_id" : "test.test",
    "user" : "test",
    "db" : "test",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
{
    "_id" : "test.read",
    "user" : "read",
    "db" : "test",
    "roles" : [
        {
            "role" : "read",
            "db" : "test"
        }
    ]
}
{
    "_id" : "test.readwrite",
    "user" : "readwrite",
    "db" : "test",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "test"
        }
    ]
}     
> db.dropUser("test")
true
温馨提示:本文最后更新于2022-12-20 20:57:50,已超过431天没有更新。某些文章具有时效性,若文章内容或图片资源有错误或已失效,请联系站长。谢谢!
转载请注明本文链接:https://blog.leonshadow.cn/763482/830.html
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享