Table of contents
Basic introduction to MongoDB
MongoDB basic concepts
Comparison of MongoDB and relational databases
MongoDB data types
MongoDB element naming rules
MongoDB installation and deployment
MongoDB configuration management
MongoDB service management
MongoDB multi-instance configuration
Basic operations
gather
Data backup and recovery
MongoDB replica set cluster deployment and management
MongoDB replica set ReplSet (replica set)
Build a MongoDB replica set cluster
Replica set election principle
Basic introduction to MongoDB
MongoDB is an open source NoSQL database system based on distributed file storage written in C++ language. In the case of high load, more nodes (instances) can be added to ensure service performance. It is used in many scenarios to replace traditional relational databases or key/value storage methods. Designed to provide scalable, high-performance data storage solutions for web applications
MongoDB provides a document-oriented storage method that is relatively simple and easy to operate and can store more complex data types. The biggest feature is that the query language supported is very powerful and its syntax is similar to the object-oriented query (Select) language. Almost all functions similar to single-table queries in relational databases can be implemented, and it also supports indexing of data. It is a collection-oriented, schema-free document database . MongoDB is a product between relational databases and non-relational databases. It is the most feature-rich among non-relational databases and is most similar to relational databases.
MongoDB currently only supports single-document transactions and is not suitable for scenarios that require complex transaction support. The flexible document model JSON format storage is closest to the real object model, is developer-friendly, and facilitates rapid development iterations. The high-availability replica set meets the requirements of high data reliability and high service availability. It has simple operation and maintenance, automatic failover, scalable sharded cluster massive data storage, and high-performance service capabilities. mmapv1, wiredtiger, mongorocks (rocksdb), in-memory and other multiple engines support to meet the needs of various scenarios. Powerful index support geographical location index can be used to build various O2O applications, text index solves search needs, TTL index solves the automatic expiration of historical data Gridfs solves the file storage needs, aggregation & mapreduce solves the data analysis scenario needs, users can write their own query statements or scripts, and distribute the requests to MongoDB for completion
From the current user application analysis on Alibaba Cloud MongoDB cloud database, MongoDB applications have penetrated into various fields, such as games, logistics, e-commerce, content management, social networking, Internet of Things, video live broadcast, etc. The following are several practical application cases.
- - In the game scene, MongoDB is used to store game user information. The user's equipment, points, etc. are directly stored in the form of embedded documents to facilitate query and update.
- - In the logistics scenario, MongoDB is used to store order information. The order status will be continuously updated during the delivery process and is stored in the form of an embedded array in MongoDB. All changes to the order can be read in one query.
- - In social scenarios, MongoDB is used to store user information and friend circle information published by users, and functions such as nearby people and places are implemented through geographical location indexing.
- - In the Internet of Things scenario, MongoDB is used to store the information of all connected smart devices and the log information reported by the devices, and perform multi-dimensional analysis on this information.
- - Live video broadcast, using MongoDB to store user information, gift information, etc.
MongoDB basic concepts
- - Document is the basic unit of data in MongoDB, which is very similar to rows (records) in relational database systems but is much more complex than the data stored in rows.
- - A collection is a group of documents. If documents in MongoDB are similar to rows in a relational database, then a collection is like a data table.
- - A single instance of MongoDB can host multiple independent databases, each with its own collections and permissions.
MongoDB comes with a simple but powerful JavaScript shell. This tool is very useful for managing MongoDB instances and operating data.
Each document has a special key "_id", which is unique in the collection in which the document is located and is equivalent to the primary key of the table in a relational database.
Comparison of MongoDB and relational databases
SQL terms/concepts |
MongoDB terminology/concepts |
explain |
database |
database |
database |
table |
collection |
Database table/collection |
row |
document |
Data record line/document |
column |
field |
Data fields/domains |
index |
index |
index |
table joins |
Table join, MongoDB does not support |
|
primary key |
primary key |
Primary key, MongoDB automatically sets the _id field as the primary key |
MongoDB data types
MongoDB element naming rules
Database naming convention:
The database name can be any UTF-8 string that meets the following conditions.
- Cannot be an empty string ("").
- May not contain ' ' (space), ., $, /, \ and \0 (null character).
- Should be all lowercase.
- Maximum 64 bytes.
Collection naming convention:
- The collection name cannot be the empty string "".
- The collection name cannot contain the \0 character (null character). This character represents the end of the collection name.
- Collection names cannot begin with "system.", which is a prefix reserved for system collections.
- There cannot be $ in the middle of the name.
Document key naming convention:
- Key cannot contain \0 (null character). This character is used to indicate the end of the key.
- . and $ have special meanings and can only be used under specific circumstances.
- Keys starting with an underscore "_" are reserved (not strictly required).
MongoDB installation and deployment
The system name was changed to MongoDB for better identification.
hostnamectl set-hostname MongoDB
bash
First turn off the firewall
iptables -F
setenforce 0
systemctl stop firewalld
Specify the maximum number of files that a process can open at the same time
[root@mongodb ~]# ulimit -n
Display the maximum number of file descriptors for the current process
[root@mongodb ~]# ulimit -n 65535
[root@mongodb ~]# ulimit -n
The settings of the ulimit command are only valid for the current session. When the user logs out, the settings will become invalid. If you need to permanently modify the file descriptor limit, you need to modify the system configuration file.
The maximum number of processes that a user can open
[root@mongodb ~]# ulimit -u
[root@mongodb ~]# ulimit -u 65535
[root@mongodb ~]# ulimit -u
Installation version download address
[root@mongodb ~]#
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.0.6.tgz
[root@mongodb ~]# tar xf mongodb-linux-x86_64-rhel70-4.0.6.tgz
[root@mongodb ~]# mv mongodb-linux-x86_64-rhel70-4.0.6 /usr/local/mongodb
[root@mongodb ~]# ln -s /usr/local/mongodb/bin/* /bin/
[root@mongodb ~ ]# mkdir -p /data/mongodb 1 //data directory
[root@mongodb ~ ]# mkdir -p /data/ logs/mongodb //Log directory
[root@mongodb ~ ]# touch /data/logs/mongodb/mongodb1.log //Log file
[root@mongodb ~]# cd /usr/local/mongodb/
[root@mongodb mongodb]# mkdir conf //Configuration file directory
[root@mongodb mongodb]# vim conf/mongodb1.conf //Configuration file
port=27017 //Listening port
dbpath=/data/mongodb1 //Specify the data directory
logpath=/data/logs/mongodb/mongodb1.log //Specify the log file path
logappend=true //Allow writing logs
fork=true //Allow creation of child processes
maxConns=5000 //Maximum number of connections
storageEngine=mmapv1 //storage engine
Start the MongoDB database, -f specifies the configuration file
[root@mongodb ~]#
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb1.conf
Used to start the MongoDB database server. The specific meaning is as follows:
`/usr/local/mongodb/bin/mongod`: Specifies the executable file path of the MongoDB server. `
-f /usr/local/mongodb/conf/mongodb1.conf`: Specify the path and file name of the configuration file. In this example, the configuration file is `/usr/local/mongodb/conf/mongodb1.conf`. By executing this command, you can start the MongoDB database server and configure it using the specified configuration file
[root@mongodb ~]# netstat -lnpt | grabbed mongod
Find and display monitoring status and corresponding process information related to MongoDB
[root@mongodb ~]# ps aux | grep mongod | grep -v grep
Find the running mongod process. The specific explanation is as follows:
- `ps aux`: Displays all running processes in the current system.
- `grep mongod`: Filter out lines containing the "mongod" keyword in the process list.
- `grep -v grep`: Filter out lines containing the "grep" keyword again to exclude the output of the grep command itself.
Taken together, the function of this command is to find and display the currently running mongod process, while excluding the output of the grep command itself.
Set to start automatically at boot
[root@mongodb mongodb]# vim /etc/rc.local
Write:
rm -f /data/mongodb1/mongod.lock
mongod -f /usr/local/mongodb/conf/mongodb1.conf
The function of this command is to delete the `mongod.lock` file in the specified path, and then use the specified configuration file to start the MongoDB database service
Connect to the database
[root@mongodb ~]# mongo
> show dbs
Some database names are reserved, and you can directly access these databases with special functions.
- admin: From a permissions perspective, this is the "root" database. If a user is added to this database, the user automatically inherits all database permissions. Certain server-side commands can also only be run from this database, such as listing all databases or shutting down the server.
- local: This data is never copied and can be used to store any collection that is local to a single server.
- config: When Mongo is used for sharding setup, the config database is used internally to save shard-related information.
MongoDB configuration management
MongoDB service management
How to shut down MongoDB:
method one:
[root@mongodb ~]# mongo
> use admin
> db.shutdownServer(); //Close the service
> exit
[root@mongodb ~]# netstat -anpt |grep mongod
Displays all TCP connections related to MongoDB and displays process information related to these connections
Displays all TCP connections related to MongoDB and displays process information related to these connections. It is found that none have been closed.
Method Two:
[root@mongodb ~]#
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb1.conf
Start the MongoDB database server (start the database first and then perform the following operations)
[root@mongodb ~]# netstat -lnpt | grabbed mongod
Query all listening connections in the current system and filter out rows containing "mongod", that is, find connections related to MongoDB
[root@mongodb ~]# /usr/local/mongodb/bin/mongod -f
/usr/local/mongodb/conf/mongodb1.conf --shutdown
Used to close the MongoDB database. The specific explanation is as follows:
- `/usr/local/mongodb/bin/mongod` is the executable file path of the MongoDB database.
- `-f /usr/local/mongodb/conf/mongodb1.conf` is the path and file name specifying the MongoDB configuration file. - `--shutdown` is an option that indicates the operation of shutting down the database.
Therefore, the meaning of this command is to close the MongoDB database using the specified configuration file
[root@mongodb ~]# netstat -lnpt | grabbed mongod
Displays all TCP connections related to MongoDB and displays process information related to these connections
netstat -lnpt | grep mongod does not show that the process is closed successfully
Method three:
[root@mongodb ~]#
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb1.conf
Start the MongoDB database server (start the database first and then perform the following operations)
[root@mongodb ~]# ps aux | grabbed mongod
View all currently running processes and filter out process information containing the "mongod" keyword
[root@mongodb ~]# kill -9 6779 //Kill the process ID
[root@mongodb ~]# netstat -lnpt | grabbed mongod
MongoDB multi-instance configuration
[root@mongodb ~]# cd /usr/local/mongodb/conf/
[root@mongodb conf]# cp mongodb{1,2}.conf
Used to copy files. in,
"mongodb{1,2}.conf" means matching two files, namely "mongodb1.conf" and "mongodb2.conf". These two files can be copied to the target location by executing this command
[root@mongodb conf]# vim mongodb2.conf (modify the red content)
port=27018
dbpath=/data/mongodb2
logpath=/data/logs/mongodb/mongodb1.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
[root@mongodb conf]# mkdir /data/mongodb2
Create MongoDB2 directory
[root@mongodb conf]# touch /data/logs/mongodb/mongodb2.log
Create the MongoDB2.log file (create the Mongodb1 file at the same time and then start)
[root@mongodb ~]#
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/mongodb2.conf
Used to start the MongoDB database server
[root@mongodb ~]# netstat -lnpt | grabbed mongod
Query all MongoDB-related network connections and corresponding process information in the current system
Write start and stop scripts
[root@mongodb ~]# vim /etc/init.d/mongodb
#!/bin/bash
INSTANCE=$1
ACTION=$2
case "$ACTION" in
'start')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/"$INSTANCE".conf;;
'stop')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/"$INSTANCE".conf --shutdown;;
'restart')
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/"$INSTANCE".conf --shutdown
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/conf/"$INSTANCE".conf;;
esac
[root@mongodb ~]# chmod +x /etc/init.d/mongodb
Grant execution permissions to the script
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 stop
Stop the MongoDB service named "mongodb1"
[root@mongodb ~]# /etc/init.d/mongodb mongodb2 stop
Stop the MongoDB service named "mongodb2"
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 start
Start the Mongodb1 service
[root@mongodb ~]# /etc/init.d/mongodb mongodb2 start
Start the Mongodb2 service
[root@mongodb ~]# netstat -lnpt | grabbed mongod
View mongodb process
Basic operations
operate |
effect |
show dbs |
View the database list under the current example, which is equivalent to show databases |
show users |
show users |
use <db_name> |
Switch current database |
db.help() |
Display database operation commands |
show collections |
Display the collections in the current database, equivalent to show tables |
db.table.help() |
Display the collection operation command. table is the current collection called table. |
db.table.find() |
Perform data search on the table collection in the current database |
Database operations
- Multiple databases can be created in one mongodb.
- MongoDB's default database is "db", which is stored in the data directory.
- A single instance of MongoDB can house multiple independent databases, each with its own collection and permissions, and different databases are also placed in different files.
[root@mongodb ~]# mongo
> show dbs
> show databases;
> db
Execute the "db" command to display the current database object or collection
> use admin
Run the "use" command to connect to a specified database
> db
gather
- - A collection is a MongoDB document group, similar to a table in RDBMS (Relational Database Management System).
- - Collections exist in databases. Collections have no fixed structure, which means that you can insert different formats and types of data into the collection, but usually the data we insert into the collection will have a certain correlation.
- - For example, we can insert documents with the following different data structures into the collection:
{"site":"www.baidu.com"}
{"site":"www.google.com","name":"Google","age":"30"}
Document operations
- - Documents are multiple sets of key-value pairs (ie BSON). MongoDB documents do not need to have the same fields, and the same fields do not need to be of the same data type. This is very different from relational databases and is also a very prominent feature of MongoDB.
- - A simple document example is as follows:
{"site":"www.crushlinux.com", "name":"crushlinux"}
have to be aware of is:
- Key/value pairs in documents are ordered.
- The values in the document can be not only strings enclosed in double quotes, but also several other data types (or even the entire embedded document).
- MongoDB is type and case sensitive.
- MongoDB documents cannot have duplicate keys.
The document's key is a string. With few exceptions, keys can use arbitrary UTF-8 characters
> use local
> show collections
> show tables
> use cloud
> db.user.insert({"id":1,"name":"Crushlinux"}); //Create a collection named user and write a document
WriteResult({ "nInserted" : 1 })
> show dbs
> show collections
> db.user.find()
> ctrl + d
In a terminal or command line interface, Ctrl + D is typically used to indicate the end of input or to exit the current session. When you finish entering commands or text in the terminal, press Ctrl + D. The system will send the input to the program or close the current terminal session.
[root@mongodb ~]# ll -h /data/mongodb1/cloud.*
Used to view detailed information about files or directories under a specified path. The specific explanation is as follows:
- `ll`: is the abbreviation of `ls -l`, used to display detailed information of files and directories.
- `-h`: is the abbreviation of `--human-readable`, used to display the file size in a human-readable manner.
- `/data/mongodb1/cloud.*`: is a wildcard expression of a file path, indicating that it matches files or directories starting with `cloud.` in the `/data/mongodb1/` directory.
Taken together, the command `ll -h /data/mongodb1/cloud.*` means to display the detailed information of the files or directories starting with `cloud.` in the `/data/mongodb1/` directory and display them in human-readable How to display file size
How to view help
[root@mongodb ~]# /usr/local/mongodb/bin/mongod --help
Used to start the MongoDB database server. The `--help` parameter indicates to display help information. After executing this command, the command line options and usage instructions of MongoDB will be displayed.
[root@mongodb ~]# mongo
> help
> db.help()
> db.version();
> db.stats();
> use cloud
> show collections
> db.user.help()
type of data
> use study
> db.t1.insert({"id":1});
> show collections
> show dbs
> db
> db.t1.insert({"id":2,"name":"Tom","isadmin":true,"gender":null,"favorite":["apple","banana","orange",1,2,3],"regtime":new Date()});
> db.t1.find()
> db.t1.findOne({'id':2});
> a = db.t1.findOne({"id":2});
> typeof(a.id)
> typeof(a.name)
> typeof(a.isadmin)
> typeof(a.gender)
> typeof(a.favorite)
> typeof(a.regtime)
>db.t1.insert({"id":3,"salary":66666666666666666666666666666,"rx":1.88888888888888888888888});
> db.t1.findOne({"id":3});
> b = db.t1.findOne({"id":3});
> typeof(b.salary)
> typeof(b.rx)
Data backup and recovery
1. Data backup method
Data import command: mongoimport
Data export export: mongoexport
Backup:
Logical backup: mongodump
Physical backup: cold backup
Restore: mongorestore
2. Copy the database
Copy the local database: db.copyDatabase("from_db","to_db","locolhost")
Copy the remote database: db.copyDatabase("from_db","to_db","192.168.200.101")
Clone collection: db.runCommand({cloneCollection:”cloud2.t1”,from:”192.168.200.101”})
How to view help:
[root@mongodb ~]# /usr/local/mongodb/bin/mongoimport --help
[root@mongodb ~]# /usr/local/mongodb/bin/mongoexport --help
[root@mongodb ~]# /usr/local/mongodb/bin/mongodump --help
Backup case
Import MySQL database content into mongodb environment
[root@mongodb ~]# yum -y install mariadb-server mariadb-devel
[root@mongodb ~]# systemctl enable mariadb
[root@mongodb ~]# systemctl start mariadb
[root@mongodb ~]# netstat -lnpt | grip :3306
[root@mongodb ~]# mysql
MariaDB [(none)]> create database cloud;
MariaDB [(none)]> use cloud
MariaDB [cloud]> create table t1(id int,name varchar(20))
MariaDB [cloud]> insert into t1 values(1,"Jack");
MariaDB [cloud]> insert into t1 values(2,"Rose");
MariaDB [cloud]> select * from t1;
Export the contents of the t1 table to the /var/lib/mysql/t1_mysql.csv file, separated by "," commas
MariaDB [cloud]> select * from t1 into outfile '/var/lib/mysql/t1_mysql.csv' fields terminated by ",";
[root@mongodb ~]# cat /var/lib/mysql/t1_mysql.csv
MongoDB replica set cluster deployment and management
MongoDB replication
The process of replicating all data changes in one database instance to another independent database instance. The default is the master-slave replication cluster (no longer used in the future). The disadvantage is that once the main database fails, the role of the main database needs to be manually switched to the most reliable slave database, and other slave databases need to be configured to synchronize with the new master database.
- Replication is the process of synchronizing data across multiple servers.
- Replication provides redundant backup of data and stores data copies on multiple servers, improving data availability and ensuring data security.
- Replication also allows you to recover data from hardware failures and service outages.
Copied Features
- Ensure data security
- Data high availability (7*24)
- Data disaster recovery
- No downtime required for maintenance (e.g. backups, reindexing, compression)
- Distributed reading of data
MongoDB replica set ReplSet (replica set)
In principle, it is also MongoDB master-slave replication technology, but when the master database fails, master-slave switching can be automatically realized, so that the failure can be recovered, and other slave databases automatically synchronize data from the new master database, and the entire process does not require manual intervention. Similar to MHA technology in MySQL.
- MongoDB replication requires at least two nodes. One of them is the master node, responsible for processing client requests, and the rest are slave nodes, responsible for replicating the data on the master node to achieve data consistency.
- The common collocation methods of each MongoDB node are: one master and one slave, one master and multiple slaves.
The master node records all operations oplog on it. The slave node periodically polls the master node to obtain these operations, and then performs these operations on its own data copy, thereby ensuring that the data of the slave node is consistent with the master node.
The MongoDB replication structure diagram is as follows:
In the above structure diagram, the client reads data from the master node. When the client writes data to the master node, the master node and the slave node interact with each other to ensure data consistency.
Characteristics of replica sets
- Cluster of N nodes
- Any node can serve as the master node
- All write operations are on the primary node
- Automatic failover
- Automatic failover
Build a MongoDB replica set cluster
Delete previous instance
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 stop
[root@mongodb ~]# /etc/init.d/mongodb mongodb2 stop
[root@mongodb ~]# rm -rf /data/
Configure 4 MongoDB instances
[root@mongodb ~]# vim /usr/local/mongodb/conf/mongodb1.conf
port=27017
dbpath=/data/mongodb1
logpath=/data/logs/mongodb/mongodb1.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
slowms=1
profile=1
replSet=crushlinux //Choose the name as you like (the four instance cluster names must be the same)
[root@mongodb ~]# vim /usr/local/mongodb/conf/mongodb2.conf
port=27018
dbpath=/data/mongodb2
logpath=/data/logs/mongodb/mongodb2.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
slowms=1
profile=1
replSet=crushlinux
[root@mongodb ~]# vim /usr/local/mongodb/conf/mongodb3.conf
port=27019
dbpath=/data/mongodb3
logpath=/data/logs/mongodb/mongodb3.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
slowms=1
profile=1
replSet=crushlinux
[root@mongodb ~]# vim /usr/local/mongodb/conf/mongodb4.conf
port=27020
dbpath=/data/mongodb4
logpath=/data/logs/mongodb/mongodb4.log
logappend=true
fork=true
maxConns=5000
storageEngine=mmapv1
slowms=1
profile=1
replSet=crushlinux
[root@mongodb ~]# mkdir /data/mongodb{1..4} -p
[root@mongodb ~]# mkdir /data/logs/mongodb -p
[root@mongodb ~]# touch /data/logs/mongodb/mongodb{1..4}.log
[root@mongodb ~]# chmod 777 /data/logs/mongodb/mongodb*
[root@mongodb ~]# ll /data/logs/mongodb/mongodb*
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 start
[root@mongodb ~]# /etc/init.d/mongodb mongodb2 start
[root@mongodb ~]# /etc/init.d/mongodb mongodb3 start
[root@mongodb ~]# /etc/init.d/mongodb mongodb4 start
[root@mongodb ~]# netstat -lnpt | grabbed mongod
[root@mongodb ~]# mongo
111:PRIMARY> rs.help() // View replication set help instructions
> rs.status()
>
cfg={"_id":"crushlinux","members":[{"_id":0,"host":"127.0.0.1:27017"},{"_id":1,"host":"127.0.0.1:27018"},{"_id":2,"host":"127.0.0.1:27019"}]}
> rs.initiate(cfg)
111x:PRIMARY> rs.status()
crushlinux:PRIMARY> rs.status() [Information inside]
{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:41:04.997Z"),
"myState" : 1,
"term" : NumberLong(1),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"appliedOpTime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"durableOpTime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1:27017",
"health" : 1, //1 is healthy, 0 is down
"state" : 1, //1 is the master, 2 is the slave
"stateStr" : "PRIMARY",
"uptime" : 125,
"optime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:40:52Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "could not find member to sync from",
"electionTime" : Timestamp(1578386449, 1),
"electionDate" : ISODate("2020-01-07T08:40:49Z"),
"configVersion" : 1,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 26,
"optime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:40:52Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:40:52Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:41:03.888Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:41:04.492Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 26,
"optime" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1578386452, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:40:52Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:40:52Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:41:03.888Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:41:04.441Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 1
}
],
"ok" : 1,
"operationTime" : Timestamp(1578386452, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386452, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
crushlinux:PRIMARY> rs.add("127.0.0.1:27020") //Add a node
{
"ok" : 1,
"operationTime" : Timestamp(1578386643, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386643, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
crushlinux:PRIMARY> rs.status()
{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:44:25.733Z"),
"myState" : 1,
"term" : NumberLong(1),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"appliedOpTime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"durableOpTime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 326,
"optime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:44:21Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1578386449, 1),
"electionDate" : ISODate("2020-01-07T08:40:49Z"),
"configVersion" : 2,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 227,
"optime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:44:21Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:44:21Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:44:25.210Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:44:24.254Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27020",
"syncSourceHost" : "127.0.0.1:27020",
"syncSourceId" : 3,
"infoMessage" : "",
"configVersion" : 2
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 227,
"optime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:44:21Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:44:21Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:44:25.210Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:44:24.255Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27020",
"syncSourceHost" : "127.0.0.1:27020",
"syncSourceId" : 3,
"infoMessage" : "",
"configVersion" : 2
},
{
"_id" : 3,
"name" : "127.0.0.1:27020",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 22,
"optime" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDurable" : {
"ts" : Timestamp(1578386661, 1),
"t" : NumberLong(1)
},
"optimeDate" : ISODate("2020-01-07T08:44:21Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:44:21Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:44:25.229Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:44:25.732Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 2
}
],
"ok" : 1,
"operationTime" : Timestamp(1578386661, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386661, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
crushlinux:PRIMARY> rs.remove("127.0.0.1:27020") //Delete node
{
"ok" : 1,
"operationTime" : Timestamp(1578386690, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386690, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
[root@mongodb ~]# ps aux | grabbed mongod
[root@mongodb ~]# kill -9 67461 //Simulate fault
[root@mongodb ~]# mongo --port 27018
.0{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:47:01.674Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1: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"),
"lastHeartbeat" : ISODate("2020-01-07T08:47:01.427Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:46:45.095Z"),
"pingMs" : NumberLong(1),
"lastHeartbeatMessage" : "Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused",
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"configVersion" : -1
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 478,
"optime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2020-01-07T08:46:56Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "could not find member to sync from",
"electionTime" : Timestamp(1578386815, 1),
"electionDate" : ISODate("2020-01-07T08:46:55Z"),
"configVersion" : 3,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 381,
"optime" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"optimeDurable" : {
"ts" : Timestamp(1578386816, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2020-01-07T08:46:56Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:46:56Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:47:01.421Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:47:01.588Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27018",
"syncSourceHost" : "127.0.0.1:27018",
"syncSourceId" : 1,
"infoMessage" : "",
"configVersion" : 3
}
],
"ok" : 1,
"operationTime" : Timestamp(1578386816, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386816, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 start
about to fork child process, waiting until server is ready for connections.
forked process: 67927
child process started successfully, parent exiting
[root@mongodb ~]# mongo --port 27018
crushlinux:PRIMARY> rs.status()
{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:48:37.546Z"),
"myState" : 1,
"term" : NumberLong(2),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"appliedOpTime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"durableOpTime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1:27017",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 29,
"optime" : {
"ts" : Timestamp(1578386906, 1),
"t" : NumberLong(2)
},
"optimeDurable" : {
"ts" : Timestamp(1578386906, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2020-01-07T08:48:26Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:48:26Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:48:35.591Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:48:36.200Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27019",
"syncSourceHost" : "127.0.0.1:27019",
"syncSourceId" : 2,
"infoMessage" : "",
"configVersion" : 3
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 574,
"optime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2020-01-07T08:48:36Z"),
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "could not find member to sync from",
"electionTime" : Timestamp(1578386815, 1),
"electionDate" : ISODate("2020-01-07T08:46:55Z"),
"configVersion" : 3,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 477,
"optime" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"optimeDurable" : {
"ts" : Timestamp(1578386916, 1),
"t" : NumberLong(2)
},
"optimeDate" : ISODate("2020-01-07T08:48:36Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:48:36Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:48:37.544Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:48:35.755Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27018",
"syncSourceHost" : "127.0.0.1:27018",
"syncSourceId" : 1,
"infoMessage" : "",
"configVersion" : 3
}
],
"ok" : 1,
"operationTime" : Timestamp(1578386916, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578386916, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
Manually switch master instance
[root@mongodb ~]# mongo --port 27018
crushlinux:PRIMARY> rs.help() //View help
crushlinux:PRIMARY> rs.freeze(30) //Pause for 30 seconds and not participate in the election
{
"operationTime" : Timestamp(1578387047, 1),
"ok" : 0,
"errmsg" : "cannot freeze node when primary or running for elec
tion. state: Primary", "code" : 95,
"codeName" : "NotSecondary",
"$clusterTime" : {
"clusterTime" : Timestamp(1578387047, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="), "keyId" : NumberLong(0)
}
}
}
crushlinux:PRIMARY> rs.stepDown(60,30) //修改成从节点
2020-01-07T16:51:20.451+0800 E QUERY [js] Error: error doing query: failed: network error while attempting to run command 'replSetStepDown' o
n host '127.0.0.1:27018' :DB.prototype.runCommand@src/mongo/shell/db.js:168:1
DB.prototype.adminCommand@src/mongo/shell/db.js:186:16
rs.stepDown@src/mongo/shell/utils.js:1444:12
@(shell):1:1
2020-01-07T16:51:20.458+0800 I NETWORK [js] trying reconnect to 127.0.0.1:27018 failed
2020-01-07T16:51:20.459+0800 I NETWORK [js] reconnect 127.0.0.1:27018 ok
crushlinux:SECONDARY> rs.status()
{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:52:23.684Z"),
"myState" : 2,
"term" : NumberLong(3),
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"appliedOpTime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"durableOpTime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1:27017",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 256,
"optime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"optimeDurable" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"optimeDate" : ISODate("2020-01-07T08:52:22Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:52:22Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:52:23.611Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:52:22.601Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1578387080, 1),
"electionDate" : ISODate("2020-01-07T08:51:20Z"),
"configVersion" : 3
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 800,
"optime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"optimeDate" : ISODate("2020-01-07T08:52:22Z"),
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 3,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 703,
"optime" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"optimeDurable" : {
"ts" : Timestamp(1578387142, 1),
"t" : NumberLong(3)
},
"optimeDate" : ISODate("2020-01-07T08:52:22Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:52:22Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:52:23.428Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:52:23.252Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "127.0.0.1:27017",
"syncSourceHost" : "127.0.0.1:27017",
"syncSourceId" : 0,
"infoMessage" : "",
"configVersion" : 3
}
],
"ok" : 1,
"operationTime" : Timestamp(1578387142, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578387142, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
[root@mongodb ~]# /etc/init.d/mongodb mongodb1 stop
killing process with pid: 67927
When simulating a mongodb1 instance failure, since the mongodb2 instance does not participate in the election, mongodb3, which is 27019, will become the new master node.
crushlinux:SECONDARY> rs.status()
{
"set" : "crushlinux",
"date" : ISODate("2020-01-07T08:53:50.785Z"),
"myState" : 2,
"term" : NumberLong(4),
"syncingTo" : "127.0.0.1:27019",
"syncSourceHost" : "127.0.0.1:27019",
"syncSourceId" : 2,
"heartbeatIntervalMillis" : NumberLong(2000),
"optimes" : {
"lastCommittedOpTime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"readConcernMajorityOpTime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"appliedOpTime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"durableOpTime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
}
},
"members" : [
{
"_id" : 0,
"name" : "127.0.0.1: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"),
"lastHeartbeat" : ISODate("2020-01-07T08:53:50.107Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:53:10.770Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused",
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"configVersion" : -1
},
{
"_id" : 1,
"name" : "127.0.0.1:27018",
"health" : 1,
"state" : 2,
"stateStr" : "SECONDARY",
"uptime" : 887,
"optime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"optimeDate" : ISODate("2020-01-07T08:53:41Z"),
"syncingTo" : "127.0.0.1:27019",
"syncSourceHost" : "127.0.0.1:27019",
"syncSourceId" : 2,
"infoMessage" : "",
"configVersion" : 3,
"self" : true,
"lastHeartbeatMessage" : ""
},
{
"_id" : 2,
"name" : "127.0.0.1:27019",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",
"uptime" : 790,
"optime" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"optimeDurable" : {
"ts" : Timestamp(1578387221, 1),
"t" : NumberLong(4)
},
"optimeDate" : ISODate("2020-01-07T08:53:41Z"),
"optimeDurableDate" : ISODate("2020-01-07T08:53:41Z"),
"lastHeartbeat" : ISODate("2020-01-07T08:53:50.068Z"),
"lastHeartbeatRecv" : ISODate("2020-01-07T08:53:49.674Z"),
"pingMs" : NumberLong(0),
"lastHeartbeatMessage" : "",
"syncingTo" : "",
"syncSourceHost" : "",
"syncSourceId" : -1,
"infoMessage" : "",
"electionTime" : Timestamp(1578387199, 1),
"electionDate" : ISODate("2020-01-07T08:53:19Z"),
"configVersion" : 3
}
],
"ok" : 1,
"operationTime" : Timestamp(1578387221, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1578387221, 1),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
Replica set election principle
1. Principle of copying
MongoDB replication is based on the operation log oplog. The oplog is equivalent to the binary log in mysql and only records changes to the data.
2. Principle of election
(1) Node type: standard node, passive node, arbitration node
- Only standard nodes may be elected as active (master) nodes and have the right to vote.
- Passive nodes have complete copies, cannot become active nodes, and have the right to vote.
- The quorum node does not copy data and cannot become an active node. It only has the right to vote.
(2) The difference between standard nodes and passive nodes
Those with higher priority values are standard nodes, and those with lower priority values are passive nodes.
(3) Election rules
The person with the highest number of votes wins, and priority is the priority value from 0 to 1000, which is equivalent to an additional number of votes from 0 to 1000.
Election results: The person with the highest number of votes wins; if the number of votes is the same, the person with the latest data wins.