Master-slave replication is a feature of MongoDB databases. It uses data backup to improve database disaster tolerance. However, because master-slave replication does not automatically implement failover, MongoDB has developed a new replication mode: Replicate Sets in version 1.6. MongoDB does not recommend that you back up data in Master-Slave mode. However, we can still learn about the master-slave replication mode of MongoDB.
1. download the latest version of MongoDB from the official MongoDB website and decompress it to a directory.
2. In the MongoDB folder, create the/data/master and/data/slave directories.
3. Start the Master node server and run the following command:
| Mongod -- dbpath/data/master -- port 10000 -- master |
After running the preceding command, mongodb generates data files and log files under data/master.
4. Start the server on the Slave node (Slave) and run the following command:
| Mongod -- dbpath/data/slave -- port 10001 -- slave -- source localhost: 10000 |
After the preceding command is executed, data files and log files are generated under data/slave, and the associated information with the master is created under the sources table in the local database.
5. Test whether Master-Slave replication (Master-Slave) takes effect.
Use "mongo localhost: 10000" to open the Master database and insert a test statement: db. test. find (); db. test. insert ({"host": "1000"}); db. test. find (); Use "mongo localhost: 10001" to open the Slave database and run the db. test. find () will find that the queried data is the same as the data queried from the Master database.
Run db. test. insert ({"girl": "lili"}); not master is displayed. This is because the Master-Slave replication mode only allows data updates from the Master database, rather than from the Slave database. Therefore, when the Master node fails, the disadvantage of being unable to switch from the Master node to the Master node is exposed.