一、MongoDB简介
MongoDB是一个开源的、面向文档的数据库管理系统,它使用NoSQL(非关系型数据库)的方式来存储数据。它是由10gen公司(现在的MongoDB公司)开发的,第一个版本于2009年发布。
MongoDB的设计目是满足大规模、高性能、可扩展的数据存储需求。它采用了JSON(JavaScript Object Notation)风格的文档模型,可以灵活地存储各种类型的数据,而不需要事先定义数据结构。这种文档模型的设计使得MongoDB能够轻松地处理复杂的数据结构,同时也提供了强大的查询和聚合功能。
MongoDB的数据存储方式是以集合(collection)为单位,每个集合中包含多个文档(document)。一个文档可以是一个JSON对象,它可以有不同的字段和值,没有固定的结构。这种设计可以方便地存储和查询不同结构的数据。
MongoDB还提供了复制和分片功能来实现高可用性和可扩展性。复制功能可以将数据复制到多个服务器上,提供数据冗余和故障恢复能力。分片功能可以将数据分布到多个服务器上,提高查询性能和存储容量。
由于MongoDB的灵活性和高性能,它被广泛应用于各种场景,如Web应用程序、大数据分析、物联网等。它支持多种编程语言和平台,并且具有丰富的工具和生态系统。
总之,MongoDB是一个强大的NoSQL数据库,它提供了灵活的数据模型和高性能的存储和查询功能,适用于各种复杂的数据存储需求。
二、MongoDB安装
1、服务器规划
序号 |
IP地址 |
操作系统 |
MongoDB版本 |
1 |
192.168.36.197 |
CentOS 7.9 |
5.0.22 |
2 |
192.168.36.198 |
CentOS 7.9 |
5.0.22 |
3 |
192.168.36.199 |
CentOS 7.9 |
5.0.22 |
2、下载MongoDB软件包
[root@localhost ~]# wget -c https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-5.0.22.tgz
3、解压MongoDB软件包
[root@localhost ~]# tar xf mongodb-linux-x86_64-rhel70-5.0.22.tgz
[root@localhost ~]# mv mongodb-linux-x86_64-rhel70-5.0.22/ /usr/local/mongodb
4、创建数据目录和日志目录和配置文件目录
[root@localhost ~]# mkdir -p /usr/local/mongodb/{data,logs,conf}
5、生成秘钥文件(任意一台机)
[root@localhost ~]# openssl rand -base64 756 >/usr/local/mongodb/keyfile
[root@localhost ~]# chmod 400 /usr/local/mongodb/keyfile
6、远程拷贝秘钥文件
[root@localhost ~]# scp /usr/local/mongodb/keyfile root@192.168.36.198:/usr/local/mongodb/
[root@localhost ~]# scp /usr/local/mongodb/keyfile root@192.168.36.199:/usr/local/mongodb/
7、创建启动文件
[root@localhost ~]# vim /usr/local/mongodb/conf/mongod.conf
# 数据库文件存放路径(目录以自己存放位置为准)
dbpath = /usr/local/mongodb/data
# 日志文件存放路径(目录以自己存放位置为准)
logpath = /usr/local/mongodb/logs/mongod.log
# Pid文件路径
pidfilepath = /var/run/mongod.pid
# 追加方式写入
logappend = true
# 副本集名称
replSet = rs1
# 副本集共享秘钥(目录以自己存放位置为准)
keyFile = /usr/local/mongodb/keyfile
# 绑定本机所有IP
bind_ip = 0.0.0.0
# 运行端口,默认27017
port = 27017
# 后台运行
fork = true
8、创建软链接
[root@localhost ~]# ln -sf /usr/local/mongodb/bin/* /usr/bin
9、创建systemctl管理配置文件
[root@localhost ~]# vim /usr/lib/systemd/system/mongod.service
[Unit]
Description=Mongodb Server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/mongodb/bin/mongod --config=/usr/local/mongodb/conf/mongod.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
[Install]
WantedBy=multi-user.target
10、启动MongoDB服务
[root@localhost ~]# systemctl daemon-reload
[root@localhost ~]# systemctl enable mongod
[root@localhost ~]# systemctl start mongod
11、查看进程和端口
[root@localhost ~]# systemctl status mongod
[root@localhost ~]# netstat -lntup
三、MongoDB副本集配置
1、初始化副本集
# 登录任意一台机器执行
[root@localhost ~]# mongo
> use admin
switched to db admin
> var replica_cluster = {
_id: "rs1",
members: [
{ _id: 0, host : "192.168.36.197:27017" },
{ _id: 1, host : "192.168.36.198:27017" },
{ _id: 2, host : "192.168.36.199:27017" }
]
};
> rs.initiate(replica_cluster);
{ "ok" : 1 }
_id:副本集名称(mongod.conf中的replSet值)
members._id:唯一值
menbers.host:主机IP:端口
初始化返回{"ok" : 1},则初始化成功
2、查看集群状态
rs1:SECONDARY> rs.status()
{
"set" : "rs1",
"date" : ISODate("2024-01-23T03:30:06.111Z"),
"myState" : 1,
"term" : NumberLong(1),
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"majorityVoteCount" : 2,
"writeMajorityCount" : 2,
"votingMembersCount" : 3,
"writableVotingMembersCount" : 3,
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"lastCommittedWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"appliedOpTime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"durableOpTime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"lastAppliedWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastDurableWallTime" : ISODate("2024-01-23T03:29:57.285Z")
},
"lastStableRecoveryTimestamp" : Timestamp(1705980587, 1),
"electionCandidateMetrics" : {
"lastElectionReason" : "electionTimeout",
"lastElectionDate" : ISODate("2024-01-23T03:28:07.241Z"),
"electionTerm" : NumberLong(1),
"lastCommittedOpTimeAtElection" : {
"ts" : Timestamp(1705980476, 1),
"t" : NumberLong(-1)
},
"lastSeenOpTimeAtElection" : {
"ts" : Timestamp(1705980476, 1),
"t" : NumberLong(-1)
},
"numVotesNeeded" : 2,
"priorityAtElection" : 1,
"electionTimeoutMillis" : NumberLong(10000),
"numCatchUpOps" : NumberLong(0),
"newTermStartDate" : ISODate("2024-01-23T03:28:07.276Z"),
"wMajorityWriteAvailabilityDate" : ISODate("2024-01-23T03:28:07.872Z")
},
"members" : [
{
"_id" : 0,
"name" : "192.168.36.197:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 1377,
"optime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2024-01-23T03:29:57Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastDurableWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "Could not find member to sync from",
"electionTime" : Timestamp(1705980487, 1),
"electionDate" : ISODate("2024-01-23T03:28:07Z"),
"configVersion" : 1,
"configTerm" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "192.168.36.198:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 129,
"optime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2024-01-23T03:29:57Z"),
"optimeDurableDate" : ISODate("2024-01-23T03:29:57Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastDurableWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastHeartbeat" : ISODate("2024-01-23T03:30:05.298Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T03:30:04.293Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.36.197:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 1
},
{
"_id" : 2,
"name" : "192.168.36.199:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 129,
"optime" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1705980597, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2024-01-23T03:29:57Z"),
"optimeDurableDate" : ISODate("2024-01-23T03:29:57Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastDurableWallTime" : ISODate("2024-01-23T03:29:57.285Z"),
"lastHeartbeat" : ISODate("2024-01-23T03:30:05.298Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T03:30:04.293Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.36.197:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 1
}
],
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1705980597, 1),
"signature" : {
"hash" : BinData(0,"FoEAmRS07NAPbIJ1wrrcgloZI38="),
"keyId" : NumberLong("7327130399279153156")
}
},
"operationTime" : Timestamp(1705980597, 1)
}
rs1:PRIMARY>
四、MongoDB添加身份验证
1、修改配置文件mongod.conf
[root@localhost ~]# vim /usr/local/mongodb/conf/mongod.conf
# 添加以下参数内容
# 开启访问控制
auth = true
2、重启MongoDB服务
[root@localhost ~]# systemctl restart mongod
3、创建用户及授权
# 创建root用户并且拥有超级管理员权限,创建test用户并且拥有test库读写权限
[root@localhost ~]# mongo
rs1:PRIMARY> use admin
switched to db admin
rs1:PRIMARY> db.createUser({user:"root",pwd:"Aa123456",roles:["root"]})
Successfully added user: { "user" : "root", "roles" : [ "root" ] }
rs1:PRIMARY> db.auth('root','Aa123456')
1
rs1:PRIMARY> use test
switched to db test
rs1:PRIMARY> db.createUser({user:"test",pwd:"Aa123456",roles:[{role:"readWrite",db:"test"}]})
Successfully added user: {
"user" : "test",
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
3、验证用户是否添加成功
# 切换任意一个节点
[root@localhost ~]# mongo
rs1:SECONDARY> rs.status()
{
"ok" : 0,
"errmsg" : "command replSetGetStatus requires authentication",
"code" : 13,
"codeName" : "Unauthorized",
"$clusterTime" : {
"clusterTime" : Timestamp(1705989225, 1),
"signature" : {
"hash" : BinData(0,"D4yfIues+56vqOEYZY1QjEC+XXY="),
"keyId" : NumberLong("7327130399279153156")
}
},
"operationTime" : Timestamp(1705989225, 1)
}
rs1:SECONDARY> use admin
switched to db admin
rs1:SECONDARY> db.auth('root','Aa123456')
1
rs1:SECONDARY> rs.status()
{
"set" : "rs1",
"date" : ISODate("2024-01-23T05:55:04.054Z"),
"myState" : 2,
"term" : NumberLong(2),
"syncSourceHost" : "192.168.36.199:27017",
"syncSourceId" : 2,
"heartbeatIntervalMillis" : NumberLong(2000),
"majorityVoteCount" : 2,
"writeMajorityCount" : 2,
"votingMembersCount" : 3,
"writableVotingMembersCount" : 3,
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"lastCommittedWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"lastAppliedWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastDurableWallTime" : ISODate("2024-01-23T05:54:55.963Z")
},
"lastStableRecoveryTimestamp" : Timestamp(1705989295, 1),
"members" : [
{
"_id" : 0,
"name" : "192.168.36.197:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 669,
"optime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2024-01-23T05:54:55Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastDurableWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"syncSourceHost" : "192.168.36.199:27017",
"syncSourceId" : 2,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 2,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "192.168.36.198:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 667,
"optime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"optimeDurable" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2024-01-23T05:54:55Z"),
"optimeDurableDate" : ISODate("2024-01-23T05:54:55Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastDurableWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastHeartbeat" : ISODate("2024-01-23T05:55:03.764Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T05:55:02.131Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1705988635, 1),
"electionDate" : ISODate("2024-01-23T05:43:55Z"),
"configVersion" : 1,
"configTerm" : 2
},
{
"_id" : 2,
"name" : "192.168.36.199:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 667,
"optime" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"optimeDurable" : {
"ts" : Timestamp(1705989295, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2024-01-23T05:54:55Z"),
"optimeDurableDate" : ISODate("2024-01-23T05:54:55Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastDurableWallTime" : ISODate("2024-01-23T05:54:55.963Z"),
"lastHeartbeat" : ISODate("2024-01-23T05:55:03.764Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T05:55:03.158Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.36.198:27017",
"syncSourceId" : 1,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 2
}
],
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1705989295, 1),
"signature" : {
"hash" : BinData(0,"qNKfkBLHtlTsxdoyee4B4pA9SnU="),
"keyId" : NumberLong("7327130399279153156")
}
},
"operationTime" : Timestamp(1705989295, 1)
}
五、MongoDB基本操作
1、创建集合/插入数据
# 创建一个名为 user 的集合,并插入一条文档。
rs1:PRIMARY> use test
switched to db test
rs1:PRIMARY> db.auth('test','Aa123456')
1
rs1:PRIMARY> db.user.insertOne({name: "Alice", age: 25, gender: "female"})
{
"acknowledged" : true,
"insertedId" : ObjectId("65af57d2cd0ed703340d94fb")
}
2、查询数据
# 主节点
rs1:PRIMARY> db.user.find()
{ "_id" : ObjectId("65af57d2cd0ed703340d94fb"), "name" : "Alice", "age" : 25, "gender" : "female" }
# 从节点默认不允许读写,如果需要执行以下操作开启。
rs1:SECONDARY> rs.secondaryOk()
rs1:SECONDARY> use test
switched to db test
rs1:SECONDARY> db.auth('test','Aa123456')
1
rs1:SECONDARY> db.user.find()
{ "_id" : ObjectId("65af57d2cd0ed703340d94fb"), "name" : "Alice", "age" : 25, "gender" : "female" }
3、故障转移
1)停止主节点MongoDB服务
[root@localhost ~]# systemctl stop mongod
2)登录任意一个节点查看主节点是否自动切换
rs1:PRIMARY> use admin
switched to db admin
rs1:PRIMARY> db.auth('root','Aa123456')
1
rs1:PRIMARY> rs.status()
{
"set" : "rs1",
"date" : ISODate("2024-01-23T06:37:29.765Z"),
"myState" : 1,
"term" : NumberLong(3),
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"majorityVoteCount" : 2,
"writeMajorityCount" : 2,
"votingMembersCount" : 3,
"writableVotingMembersCount" : 3,
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"lastCommittedWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"appliedOpTime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"durableOpTime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"lastAppliedWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"lastDurableWallTime" : ISODate("2024-01-23T06:37:28.209Z")
},
"lastStableRecoveryTimestamp" : Timestamp(1705991808, 1),
"electionCandidateMetrics" : {
"lastElectionReason" : "stepUpRequestSkipDryRun",
"lastElectionDate" : ISODate("2024-01-23T06:35:08.191Z"),
"electionTerm" : NumberLong(3),
"lastCommittedOpTimeAtElection" : {
"ts" : Timestamp(1705991706, 1),
"t" : NumberLong(2)
},
"lastSeenOpTimeAtElection" : {
"ts" : Timestamp(1705991706, 1),
"t" : NumberLong(2)
},
"numVotesNeeded" : 2,
"priorityAtElection" : 1,
"electionTimeoutMillis" : NumberLong(10000),
"priorPrimaryMemberId" : 1,
"numCatchUpOps" : NumberLong(0),
"newTermStartDate" : ISODate("2024-01-23T06:35:08.200Z"),
"wMajorityWriteAvailabilityDate" : ISODate("2024-01-23T06:35:08.247Z")
},
"members" : [
{
"_id" : 0,
"name" : "192.168.36.197:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 3214,
"optime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"optimeDate" : ISODate("2024-01-23T06:37:28Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"lastDurableWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1705991708, 1),
"electionDate" : ISODate("2024-01-23T06:35:08Z"),
"configVersion" : 1,
"configTerm" : 3,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "192.168.36.198:27017",
"health" : 0,
"state" : 8,
"stateStr" : "(not reachable/healthy)",
"uptime" : 0,
"optime" : {
"ts" : Timestamp(0, 0),
"t" : NumberLong(-1)
},
"optimeDurable" : {
"ts" : Timestamp(0, 0),
"t" : NumberLong(-1)
},
"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
"optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T06:35:06.084Z"),
"lastDurableWallTime" : ISODate("2024-01-23T06:35:06.084Z"),
"lastHeartbeat" : ISODate("2024-01-23T06:37:28.291Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T06:35:08.202Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "Error connecting to 192.168.36.198:27017 :: caused by :: Connection refused",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 2
},
{
"_id" : 2,
"name" : "192.168.36.199:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 3213,
"optime" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"optimeDurable" : {
"ts" : Timestamp(1705991848, 1),
"t" : NumberLong(3)
},
"optimeDate" : ISODate("2024-01-23T06:37:28Z"),
"optimeDurableDate" : ISODate("2024-01-23T06:37:28Z"),
"lastAppliedWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"lastDurableWallTime" : ISODate("2024-01-23T06:37:28.209Z"),
"lastHeartbeat" : ISODate("2024-01-23T06:37:28.228Z"),
"lastHeartbeatRecv" : ISODate("2024-01-23T06:37:28.228Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncSourceHost" : "192.168.36.197:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1,
"configTerm" : 3
}
],
"ok" : 1,
"$clusterTime" : {
"clusterTime" : Timestamp(1705991848, 1),
"signature" : {
"hash" : BinData(0,"b2icuhAxHpXvFc8Po40sVdj5CfY="),
"keyId" : NumberLong("7327130399279153156")
}
},
"operationTime" : Timestamp(1705991848, 1)
}
从返回结果来看,主节点已经切换至192.168.36.197这个机器,原来的主节点192.168.36.198健康状态也变成了0。
若文章图片、下载链接等信息出错,请在评论区留言反馈,博主将第一时间更新!如本文“对您有用”,欢迎随意打赏,谢谢!
评论