自建 MongoDB 实践:MongoDB 的安装及基本使用

pivoteic
发布于 2023-7-10 16:03
浏览
0收藏

远程连接

刚才我们是以 ​localhost​ 的形式连接到该实例的,那么如何远程连接该实例呢?我们依然可以使用 mongo shell 或图形化的工具来连接。默认情况下,MongoDB 只监听了 127.0.0.1 的 27017 端口,我们需要修改一下配置,使其监听 10.20.20.19 地址。修改 ​/etc/mongod.conf​

net:
  port: 27017
  bindIp: 127.0.0.1,10.20.20.19  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.

修改完配置后,重启服务并验证端口是已监听:

(venv36) [root@mongo01 ~]# systemctl restart mongod(venv36) [root@mongo01 ~]# netstat -antup |grep 27017tcp        0      0 127.0.0.1:27017         0.0.0.0:*               LISTEN      15549/mongod        tcp        0      0 10.20.20.19:27017       0.0.0.0:*               LISTEN      15549/mongod

接下来我们看看如何使用 mongo shell 连接。

➜  mongodb-macos-x86_64-4.4.15 ./bin/mongo 10.20.20.19/admin -u tyun -p
MongoDB shell version v4.4.15
Enter password: 
connecting to: mongodb://10.20.20.19:27017/admin?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("419bb64a-6ce8-4d4a-be54-b916f4a06ad2") }
MongoDB server version: 4.4.15
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> exit
bye

在服务端我们可以看下日志,由于日志是 JSON 格式,我们把它美化一下:

{
    "t": {
        "$date": "2022-07-29T06:06:16.551+00:00"
    },
    "s": "I",
    "c": "NETWORK",
    "id": 51800,
    "ctx": "conn2",
    "msg": "client metadata",
    "attr": {
        "remote": "192.168.100.134:58230",
        "client": "conn2",
        "doc": {
            "application": {
                "name": "MongoDB Shell"
            },
            "driver": {
                "name": "MongoDB Internal Client",
                "version": "4.4.15"
            },
            "os": {
                "type": "Darwin",
                "name": "Mac OS X",
                "architecture": "x86_64",
                "version": "21.5.0"
            }
        }
    }
}
{
    "t": {
        "$date": "2022-07-29T06:06:16.612+00:00"
    },
    "s": "I",
    "c": "ACCESS",
    "id": 20250,
    "ctx": "conn2",
    "msg": "Authentication succeeded",
    "attr": {
        "mechanism": "SCRAM-SHA-256",
        "speculative": true,
        "principalName": "tyun",
        "authenticationDatabase": "admin",
        "remote": "192.168.100.134:58230",
        "extraInfo": {}
    }
}

远程命令行连接没有问题。我们再试试图形化工具是否可以正常连接。

自建 MongoDB 实践:MongoDB 的安装及基本使用-鸿蒙开发者社区

自建 MongoDB 实践:MongoDB 的安装及基本使用-鸿蒙开发者社区

这里推荐使用 MongoDB Compass 图形化管理工具(目前可以免费使用):

首先新建连接:

自建 MongoDB 实践:MongoDB 的安装及基本使用-鸿蒙开发者社区

之后就可以像下面这样使用了:

自建 MongoDB 实践:MongoDB 的安装及基本使用-鸿蒙开发者社区

至此,一个基本可用的 MongoDB 实例算是安装及配置完成了。接下来的内容我们一起看下 MongoDB 如何使用。

常用操作

在介绍如何使用 MongoDB 之前,我们需要介绍一下如何创建库、用户及授权。

use 命令

use 命令类似于 MySQL 中的 use,不过还有点区别,如果数据库不存在,则创建。

# 语法为
> use <db_name>

# 一个例子
> use order
switched to db order

> db.orders.insert({name: "underwear", price: 20})
WriteResult({ "nInserted" : 1 })

> db.orders.find()
{ "_id" : ObjectId("62e764b8e62e3a8595db3641"), "name" : "underwear", "price" : 20 }

> db.orders.find().pretty()
{
"_id" : ObjectId("62e764b8e62e3a8595db3641"),
"name" : "underwear",
"price" : 20
}

这样就创建了一个名为 order 的库及名为 orders 的集合(表)并插入了一条文档。

show 命令

// 查看数据库,语法为:
show dbs or show databases

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
order   0.000GB
test    0.000GB

> show databases
admin   0.000GB
config  0.000GB
local   0.000GB
order   0.000GB
test    0.000GB

// 查看结合,语法为:
show collections or show tables

> show collections
orders

> show tables
orders

// 查看用户
show users

> use admin
switched to db admin

> show users
{
"_id" : "admin.admin",
"userId" : UUID("5701b2b3-cb50-4c50-ba48-3deda0977a8f"),
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
{
"_id" : "admin.tyun",
"userId" : UUID("c1051c23-23ca-48c7-81c4-34b0fe22a5c2"),
"user" : "tyun",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

// 查看角色
show roles

> show roles
{
"role" : "__queryableBackup",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "__system",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "backup",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "clusterAdmin",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "clusterManager",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "clusterMonitor",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "dbAdmin",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "dbAdminAnyDatabase",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "dbOwner",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "enableSharding",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "hostManager",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "read",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "readAnyDatabase",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "readWrite",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "readWriteAnyDatabase",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "restore",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "root",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "userAdmin",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}
{
"role" : "userAdminAnyDatabase",
"db" : "admin",
"isBuiltin" : true,
"roles" : [ ],
"inheritedRoles" : [ ]
}

查看当前数据库,直接使用 db 命令。

> db
test

用户授权

// 创建数据库:
use test
db.customer.insert({id: 1, memo: "create database", cdate: new Date()})

// 创建用户(读写权限):
> use admin
> db.createUser({user: "readerwriter", pwd: "writer123", roles: [{role: "readWrite", db: "test"}]});
Successfully added user: {
"user" : "readerwriter",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}

// 创建用户(对 test 库有只读权限):
> use admin
> db.createUser({user: "reader", pwd: "reader123", roles: [{role: "read", db: "test"}]})
Successfully added user: {
"user" : "reader",
"roles" : [
{
"role" : "read",
"db" : "test"
}
]
}

我们退出当前 mongo shell,然后以 reader 用户登录到 MongoDB 中,

> exit
bye

[root@mongo01 ~]# mongo --authenticationDatabase "admin" -u "reader" -p
MongoDB shell version v4.4.15
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4fc423cf-d502-4511-bc2f-fdb4d452b45d") }
MongoDB server version: 4.4.15
> show dbs
test  0.000GB

> show tables
customer
inventory
oscars

接着我们插入一条数据进行验证:

> db.customer.insert({id: 2, "memo": "i can insert doc?", "cdate": new Date()})
WriteCommandError({
"ok" : 0,
"errmsg" : "not authorized on test to execute command { insert: \"customer\", ordered: true, lsid: { id: UUID(\"4fc423cf-d502-4511-bc2f-fdb4d452b45d\") }, $db: \"test\" }",
"code" : 13,
"codeName" : "Unauthorized"
})

接着我们验证 readerwriter 用户,

> exit
bye

[root@mongo01 ~]# mongo --authenticationDatabase "admin" -u "readerwriter" -p
MongoDB shell version v4.4.15
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("46071731-410c-4b26-a3f7-b5ef36186e21") }
MongoDB server version: 4.4.15
> show dbs
test  0.000GB

> use test
switched to db test

> show tables
customer
inventory
oscars

// 插入一条文档
> db.customer.insert({id: 2, "memo": "i can insert doc?", "cdate": new Date()})
WriteResult({ "nInserted" : 1 })

// 查看文档
> db.customer.find().pretty()
{
"_id" : ObjectId("62e76836e62e3a8595db3642"),
"id" : 1,
"memo" : "create database",
"cdate" : ISODate("2022-08-01T05:44:22.024Z")
}
{
"_id" : ObjectId("62e76b041abf99a6e2870558"),
"id" : 2,
"memo" : "i can insert doc?",
"cdate" : ISODate("2022-08-01T05:56:20.410Z")
}

// 删除一条文档
> db.customer.deleteOne({id: 2})
{ "acknowledged" : true, "deletedCount" : 1 }

> db.customer.find().pretty()
{
"_id" : ObjectId("62e76836e62e3a8595db3642"),
"id" : 1,
"memo" : "create database",
"cdate" : ISODate("2022-08-01T05:44:22.024Z")
}

删除用户

> use admin
switched to db admin

> db.runCommand({dropUser: "reader"})
{ "ok" : 1 }

总结

好了,今天就为大家介绍这么多。主要是 MongoDB 的一些安装配置及基本操作、介绍了图形化管理工具、远程连接、简单的用户授权等。后面的章节会继续为大家介绍相关的其他话题,请大家继续关注,别走开。


文章转载自公众号:新钛云服


分类
标签
已于2023-7-10 16:03:02修改
收藏
回复
举报
回复
    相关推荐