MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable high-performance data storage solutions for WEB applications. — Baidu Baike (too lazy to write concepts)

Common MongoDB commands

1.1 Database Startup

Command line startup:

./mongod -dbpath /mongodb/db -logpath /mongodb/log/mongo.log -fork
Copy the code

Configuration file startup:

./mongod -f  /mongodb/mongo.conf
Copy the code

Database shutdown:

1. Kill the process

> ps - ef | grep mongo, 501, 6187, 956 0 2:11 afternoon ttys001 0:36. 65 / Users/kux_testMac/soft/mongo/bin/mongod - f / Users/kux_testMac/soft/mongo/mongo. Conf, 501, 6221, 4299 0 2:11 afternoon ttys006 0:00. 33. / mongo, 501, 8797, 6232 0 4:19 ttys007 in the afternoon 00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn mongo kux_testMac@zyquan-2:~/soft/mongodb/bin| >kill -9 6187
kux_testMac@zyquan-2:~/soft/mongodb/bin|
> 

Copy the code

2. Run the db command: Note that only root users can run db.shutdowbserver ().

> db.shutdownServer()
2020-04-27T08:18:18.950+0000 I  NETWORK  [js] DBClientConnection failed to receive message from 127.0.0.1:27017 - HostUnreachable: Connection closed by peer
server should be down...
Copy the code

1.2 Configuration Files

# Log file location: change to the actual path
logpath=/root/mongodb/logs/mongo.log
# database storage location: change to actual path
dbpath=/root/mongodb/data/
Write to the log appending
logappend=true
# port
port=27017
Whether to run as a daemon
fork=true
# Whether to run in authentication mode
auth=true

Enable periodic logging of CPU utilization and I/O wait
#cpu = true
Record the output in detail
#verbose = true
# Inspect all client data for validity on receipt (useful for
# Developing Drivers) is used to validate client requests while developing drivers
# objcheck = true
# Enable db quota management
Enable database quota management
# quota = true
Set the oplog record level
# Set oplogging level where n is
# 0=off (default)
# 1=W
# 2=R
# 3=both
# 7=W+some reads
# diaglog=0
Diagnostic/debugging option Dynamic debugging items
# nocursors = true
# Ignore Query hints Ignores query hints
# nohints = true
# disable HTTP interface, default localhost: 28017
# nohttpinterface = true
# Turn off server-side scripting, which greatly limits functionality
# Turns off server-side scripting. This will result in greatly limited
# functionality
# noscripting = true
# close the scan table, any query will fail the scan
# Turns off table scans. Any query that would do a table scan fails.
# notablescan = true
Turn off data file preallocation
# Disable data file preallocation.
# noprealloc = true
Specifies the size of the.ns file for the new database, in MB
# Specify .ns file size for new databases.
# nssize = 
# Replication Options Replica set Options
# in replicated mongo databases, specify the replica set name here
# replSet=setname
# maximum size in megabytes for replication operation log
# oplogSize=1024
# path to a key file storing authentication info for connections
# between replica set members
# specify the path to the key file where authentication information is stored
# keyFile=/path/to/keyfile
Copy the code

1.3 Database Backup and Restoration

Assume that the database user name and password are admin and kux

Backup database:

./mongodump --username admin --password kux --authenticationDatabase admin
Copy the code

Restore database:

Note: E:/test stores the database file backed up in the previous step

/mongorestore -h 127.0.0.1:27017 -u admin -p kux --authenticationDatabase admin -dtest E:/test
Copy the code

2. MongoDB user authorization

2.1 MongoDB is installed without authorization. You can use mongo command to directly connect to the database

root@36ec95eccef3:/usr/bin# ./mongoMongo shell version v4.2.6 connecting to: mongo: / / 127.0.0.1:27017 /? compressors=disabled&gssapiServiceName=mongodb Implicit session: session {"id" : UUID("5918b349-a425-4cac-af01-e3cf68e584ad"} MongoDB server version: 4.2.6 >Copy the code

2.2 Creating the admin Super Administrator

#customDate is a custom data, optional
#userAdminAnyDatabase is the user role
>use admin
db.createUser(  
  { 
     user: "admin".pwd: "admin",  
     customDate:"xxx"Roles: [{role:"userAdminAnyDatabase", db: "admin"}]})Copy the code

2.3 Enabling Access control

Enable access control by adding the –auth option at startup or by adding auth=true to the configuration file. And restart the instance

./mongod -dbpath /mongodb/db -logpath /mongodb/log/mongo.log --auth
Copy the code
# Whether to run in authentication mode
auth=true
Copy the code

2.4 User Authentication

You can verify user permissions at mongo Shell login

root@36ec95eccef3:/usr/bin# ./mongo -u admin -p admin --authenticationDatabase adminMongo shell version v4.2.6 connecting to: mongo: / / 127.0.0.1:27017 /? authSource=admin&compressors=disabled&gssapiServiceName=mongodb Implicit session: session {"id" : UUID("9f00cee6-d24d-49b0-9437-50a228d2ce38"} MongoDB server version: 4.2.6 > use admin switched to db admin > show users {"_id" : "admin.admin"."userId" : UUID("6cbfae29-0a66-400e-a206-b065e11af182"),
	"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} >Copy the code

You can also use db.auth for verification after entering the Mongo shell

> db.auth('admin'.'admin')
1
> show users
{
	"_id" : "admin.admin"."userId" : UUID("6cbfae29-0a66-400e-a206-b065e11af182"),
	"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} >Copy the code

2.5 Creating a Common User

A common user, user1, is created, and a database, Eva, is created. User1 now has dbOwner privileges for database Eva

> db.createUser( ... {... user:"user1".pwd: "pwd1". roles: [ ... { role:"dbOwner", db: "eva"}... ] . }...). Successfully added user: {"user" : "user1"."roles": [{"role" : "dbOwner"."db" : "eva"}}]Copy the code

With access to data Eva using user1 account, we can test it.

root@36ec95eccef3:/usr/bin# ./mongo -u user1 -p pwd1 --authenticationDatabase evaMongo shell version v4.2.6 connecting to: mongo: / / 127.0.0.1:27017 /? authSource=eva&compressors=disabled&gssapiServiceName=mongodb Implicit session: session {"id" : UUID("1ebd017b-95d5-4688-b17d-42b3de454964"} MongoDB server version: 4.2.6 > use Eva switched to DB Eva > show DBS > show users {"_id" : "eva.user1"."userId" : UUID("f38602a6-4578-4c71-b1b1-1c48923946e6"),
   "user" : "user1"."db" : "eva"."roles": [{"role" : "dbOwner"."db" : "eva"}]."mechanisms" : [
   	"SCRAM-SHA-1"."SCRAM-SHA-256"]} >Copy the code

Db.createuser creates a user in a database, such as admin, or in a database created by Mongodb. Whether you use admin or use your own data in the console in the first place.

In Mongodb –authenticationDatabase also refers to the user’s database.

use admin > db.createUser( ... {... user:"pmtools".pwd: "pwd1". roles: [ ... { role:"dbOwner", db: "pmtools"}... ] . }...).Copy the code

For authorization — the database used by authenticationDatabase is admin, but he has dbOwner permission for database PMTools

The admin database of Mongodb is a special database

2.6 Operations performed by Other Users

Viewing User Information

> db.getUser("user1", { showPrivileges: true{})"_id" : "eva.user1"."userId" : UUID("f38602a6-4578-4c71-b1b1-1c48923946e6"),
	"user" : "user1"."db" : "eva"."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]."roles": [{"role" : "dbOwner"."db" : "eva"}]."inheritedRoles": [{"role" : "dbOwner"."db" : "eva"}]."inheritedPrivileges": [{"resource" : {
				"db" : "eva"."collection" : ""
			},
			"actions" : [
				"bypassDocumentValidation"."changeCustomData"."changePassword"."changeStream"."collMod"."collStats"."compact"."convertToCapped"."createCollection"."createIndex"."createRole"."createUser"."dbHash"."dbStats"."dropCollection"."dropDatabase"."dropIndex"."dropRole"."dropUser"."emptycapped"."enableProfiler"."find"."grantRole"."insert"."killCursors"."listCollections"."listIndexes"."planCacheIndexFilter"."planCacheRead"."planCacheWrite"."reIndex"."remove"."renameCollectionSameDB"."revokeRole"."setAuthenticationRestriction"."storageDetails"."update"."validate"."viewRole"."viewUser"] {},"resource" : {
				"db" : "eva"."collection" : "system.js"
			},
			"actions" : [
				"changeStream"."collStats"."convertToCapped"."createCollection"."createIndex"."dbHash"."dbStats"."dropCollection"."dropIndex"."emptycapped"."find"."insert"."killCursors"."listCollections"."listIndexes"."planCacheRead"."remove"."renameCollectionSameDB"."update"] {},"resource" : {
				"db" : "eva"."collection" : "system.profile"
			},
			"actions" : [
				"changeStream"."collStats"."convertToCapped"."createCollection"."dbHash"."dbStats"."dropCollection"."find"."killCursors"."listCollections"."listIndexes"."planCacheRead"]}],"inheritedAuthenticationRestrictions": []} >Copy the code

To add a role for a user, use the super administrator account

> db.grantRolesToUser("user1", [{role: "readWrite", db: "test"}])
> show users
{
	"_id" : "admin.admin"."userId" : UUID("6cbfae29-0a66-400e-a206-b065e11af182"),
	"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} {"_id" : "admin.user1"."userId" : UUID("22d5e21c-1870-4ebd-9b79-28ec5ee1a538"),
	"user" : "user1"."db" : "admin"."roles": [{"role" : "readWrite"."db" : "test"
		},
		{
			"role" : "dbOwner"."db" : "eva"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} >Copy the code

Updating User Information

>  db.updateUser('user1',{roles: [{role: "dbOwner", db: "eva"}]})
> show users
{
	"_id" : "admin.admin"."userId" : UUID("6cbfae29-0a66-400e-a206-b065e11af182"),
	"user" : "admin"."db" : "admin"."roles": [{"role" : "userAdminAnyDatabase"."db" : "admin"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} {"_id" : "admin.user1"."userId" : UUID("22d5e21c-1870-4ebd-9b79-28ec5ee1a538"),
	"user" : "user1"."db" : "admin"."roles": [{"role" : "dbOwner"."db" : "eva"}]."mechanisms" : [
		"SCRAM-SHA-1"."SCRAM-SHA-256"]} >Copy the code
> db.runCommand(
    {
        updateUser: "user1",
        roles: [
            { role: "dbOwner", db: "eva"]})},Copy the code

Recall a User Role

> use admin
> db.revokeRolesFromUser(
    "user1",
    [
        { role: "read", db: "test"}])Copy the code
> use admin
> db.runCommand(
    {
        revokeRolesFromUser: "user1",
        roles:
            [
                { role: "read", db: "test"}]})Copy the code

Changing a User password

> use admin
> db.changeUserPassword("user1"."pwd2")
Copy the code

Delete user

> use admin
> db.dropUser("user1")
Copy the code
> use admin
> db.runCommand({ dropUser: "dbabd_user" })
Copy the code

2.7 MongoDB Built-in Roles

Character classification Character name Role description
Database user read Allows the user to read the specified database
Database user readWrite Allows users to read and write to specified databases
Database administrator dbAdmin Allows users to create and delete indexes, view statistics, or access system.profile, but does not have role and user management rights.
Database administrator userAdmin Provides the ability to create and modify roles and users in the current database;
Database administrator dbOwner Provides the ability to perform any operation on the database. This role combines the privileges granted by the readWrite, dbAdmin, and userAdmin roles;
Cluster Management Role hostManager Provides the ability to monitor and manage servers
Cluster Management Role clusterManager Provide administrative and monitoring operations on the cluster. Access to configuration and local databases for sharding and replication, respectively;
Cluster Management Role clusterMonitor Provides read-only access to monitoring tools
Cluster Management Role clusterAdmin Provides the most powerful cluster management access (replica sets, sharding, master slave, and so on). The ability to combine the clusterManager, clusterMonitor, and hostManager roles, as well as the dropDatabase operation
Backup and Restoration Roles backup Provide the capabilities required to back up data
Backup and Restoration Roles restore Provide the ability to restore data using MongoRestore;
All database roles readAnyDatabase It is available only in the admin database and is granted the read permission of all databases
All database roles readWriteAnyDatabase This parameter is available only in the admin database and is granted read and write permission to all databases
All database roles userAdminAnyDatabase Only available in the admin database, the user is granted the userAdmin permission of all databases
All database roles dbAdminAnyDataBase Only available in the admin database, the user is granted the adAdmin permission of all databases
Superuser role root Super permission, only for the admin library;
Internal role __system Provides privileges for any operation on any object in the database

2.8 customizing mongodb Roles

In general, mongodb built-in roles are sufficient. If the built-in roles do not meet the requirements, you can use db.createrole () to customize the roles.

When creating a Role, four characteristics of a Role must be identified:

  • Scope: specifies the Scope of the role. The role created in Admin can be used by other DB users. A role created in another DB can only be used in the current DB.
  • Resource: Resource controlled by a role, indicating that the permission to perform specific operations on the Resource is granted.
  • Privilege Actions: Defines the Actions that users can perform on resources. The system defines Actions as “Privilege Actions”.
  • Inherit: The role can Inherit the rights of other roles

Note that roles created in the admin database, Scope is global, can be used in admin, other DB, and cluster, and can inherit other DB roles; For roles not created in admin, Scope is the current database, can only be used in the current DB, can only inherit the current database role.

How to use Docker to run MongoDB

3.1. The installation of the docker

Specific installation methods www.runoob.com/docker/maco…

Get. Daocloud. IO /

Modify docker download source to domestic address after installation

Check the Docker version after the installation is successful

Crooked Docker -- Version Docker Version 19.03.5, Build 633A0EACopy the code

3.2 Downloading the Mongo Image

First search mongo image:

> Docker search Mongo NAME DESCRIPTION STARS AUTOMATED Mongo MongoDB document Databases provide high avai... 6804 [OK] . . .Copy the code

The first mongo was the official Mongo image

> docker pull mongo
Copy the code

View the downloaded image:

Tail Docker Image Ls REPOSITORY TAG Image ID CREATED SIZE Mongo latest 3f3DAF863757 4 days ago 388MB Ubuntu Latest 549b9B86CB8d 4 months ago 64.2MB Hello-world latest FCE289E99eb9 16 months ago 1.84kBCopy the code

3.3 Running containers

The simplest command

#--name specifies the container name
# -p 27017:27107 corresponds to the native port: container port mapping
# -d Run as a daemon
# mongo is the corresponding mongo containerCat cat cat cat cat cat cat Cat Cat Cat Cat Cat cat cat catCopy the code

View the mirror

Tail Docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES dac2AE3B1C4A mongo"Docker - entrypoint. S..."28 seconds ago Up 27 seconds 0.0.0.0:27017->27017/ TCP mymongoCopy the code

Enable the authorization mode and change the port number running in the container:

docker run --name mymongo -p 27017:27018 -d mongo --auth --port=27018
Copy the code

Stop the container

Crooked Docker stop Mymongo MymongoCopy the code

Remove the container

Crooked Docker rm Mymongo MymongoCopy the code

4.MongoDB Replica Sets

4.1 Why Not Master-slave Replication (Master-slave)

Master-slave replication is the most common replication method of MongoDB. It is also a simple cluster technology for database synchronous backup, which is very flexible. Can be used for backup, failover, read expansion, etc. The basic setup is to create a master node and one or more slave nodes, each of which knows the address of the master node. If the active node fails in two-node backup, you need to manually select a secondary node to replace the host to continue services. So master-slave replication is not suitable for production, and MongoDB has removed master-slave replication since version 3.2.

Replica sets have replaced master slave replication in most cases. Replica sets are more suitable for production use, in addition to providing all the functionality of master-slave replication.

4.2. Replica set principle

A replica set is a group that maintains the same data setmongodInstance. A replica set contains several data bearer nodes and (optionally) a mediator node. In the data hosting node, only one member is treated as the primary node, while the other nodes are treated as secondary nodes.

In the event of a Master failure, the Master can automatically vote to elect a new Master and direct the remaining Slave servers to connect to the new Master, a process that is transparent to the application. You can say that MongoDB replica sets are master-slave replicates with failover capabilities.

You can also configure an additional quorum node

4.3 Configuring a Replica Set

1 Start three Mongo services (you can also start them from configuration files)

# dbpath: database storage address, --port port number, --fork background run --syslog Use system logs, replSet copy set name is kux.mongod --dbpath=.. /db1 --port=27018 --fork --syslog --replSet=kux mongod --dbpath=.. /db2 --port=27019 --fork --syslog --replSet=kux mongod --dbpath=.. /db3 --port=27020 --fork --syslog --replSet=kuxCopy the code

We preset port 27018 as the master node, 27019 as the slave node, and 27020 as the quorum node

Log in to 27018 using shell

 mongo localhost:27018
Copy the code

2. Initialize the replica set/set the local host as the master node

> rs.initiate()
{
	"ok": 0."errmsg" : "This node was not started with the replSet option"."code" : 76,
	"codeName" : "NoReplicationEnabled"
}
> 
Copy the code

Enter the shell several times to find the SECONDARY node changed to the PRIMARY node

kux:SECONDARY> 
kux:PRIMARY> 
kux:PRIMARY> 
kux:PRIMARY> 
Copy the code

You can also view the current configuration

 kux:PRIMARY> rs.conf()
{
	"_id" : "kux"."version" : 1,
	"protocolVersion" : NumberLong(1),
	"writeConcernMajorityJournalDefault" : true."members": [{"_id": 0."host" : "localhost:27018"."arbiterOnly" : false."buildIndexes" : true."hidden" : false."priority" : 1,
			"tags": {},"slaveDelay" : NumberLong(0),
			"votes": 1}]."settings" : {
		"chainingAllowed" : true."heartbeatIntervalMillis" : 2000,
		"heartbeatTimeoutSecs" : 10,
		"electionTimeoutMillis" : 10000,
		"catchUpTimeoutMillis": 1,"catchUpTakeoverDelayMillis" : 30000,
		"getLastErrorModes": {},"getLastErrorDefaults" : {
			"w" : 1,
			"wtimeout": 0}."replicaSetId" : ObjectId("5eaa3720074889fad47be807")
	}
}
kux:PRIMARY> 
Copy the code
  1. Add 27019 as the secondary node
kux:PRIMARY> rs.add('localhost:27019')
{
	"ok" : 1,
	"operationTime" : Timestamp(1588213805, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1588213805, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
kux:PRIMARY> 
Copy the code

4. Add 27020 as the quorum node

kux:PRIMARY> rs.addArb('localhost:27020')
{
	"ok" : 1,
	"operationTime" : Timestamp(1588213864, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1588213864, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
Copy the code

View the current replica set status

kux:PRIMARY> rs.status()
{
	"set" : "kux"."date" : ISODate("The 2020-04-30 T02:31:32. 801 z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"syncingTo" : ""."syncSourceHost" : ""."syncSourceId": 1,"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1588213888, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1588213888, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1588213888, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1588213888, 1),
			"t" : NumberLong(1)
		}
	},
	"lastStableCheckpointTimestamp" : Timestamp(1588213838, 1),
	"members": [{"_id": 0."name" : "localhost:27018"."health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY"."uptime" : 457,
			"optime" : {
				"ts" : Timestamp(1588213888, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2020-04-30T02:31:28Z"),
			"syncingTo" : ""."syncSourceHost" : ""."syncSourceId": 1,"infoMessage" : ""."electionTime" : Timestamp(1588213536, 2),
			"electionDate" : ISODate("2020-04-30T02:25:36Z"),
			"configVersion": 3."self" : true."lastHeartbeatMessage" : ""
		},
		{
			"_id" : 1,
			"name" : "localhost:27019"."health" : 1,
			"state": 2."stateStr" : "SECONDARY"."uptime" : 87,
			"optime" : {
				"ts" : Timestamp(1588213888, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1588213888, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2020-04-30T02:31:28Z"),
			"optimeDurableDate" : ISODate("2020-04-30T02:31:28Z"),
			"lastHeartbeat" : ISODate("The 2020-04-30 T02:31:32. 160 z"),
			"lastHeartbeatRecv" : ISODate("The 2020-04-30 T02:31:32. 160 z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : ""."syncingTo" : "localhost:27018"."syncSourceHost" : "localhost:27018"."syncSourceId": 0."infoMessage" : ""."configVersion": 3}, {"_id": 2."name" : "localhost:27020"."health" : 1,
			"state" : 7,
			"stateStr" : "ARBITER"."uptime": 28."lastHeartbeat" : ISODate("The 2020-04-30 T02:31:32. 160 z"),
			"lastHeartbeatRecv" : ISODate("The 2020-04-30 T02:31:32. 243 z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : ""."syncingTo" : ""."syncSourceHost" : ""."syncSourceId": 1,"infoMessage" : ""."configVersion": 3}],"ok" : 1,
	"operationTime" : Timestamp(1588213888, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1588213888, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
kux:PRIMARY> 
Copy the code

5. Validate the replica set

Start by building a test database on the primary repository

kux:PRIMARY> use test
switched to db test
kux:PRIMARY> db.test.insert({name: 'zyquan', phonenumber: '1866579xxxx'})
WriteResult({ "nInserted" : 1 })
kux:PRIMARY> db.test.find()
{ "_id" : ObjectId("5eaa3965e5c7a96472a041ce"), "name" : "zyquan", "phonenumber" : "1866579xxxx" }
kux:PRIMARY> 
Copy the code

Mysql > alter database 27019; mysql > alter database 27019; mysql > alter database 27019

⇒ ps - ef | grep mongod 501 2100 1 0 so morning?? 0:03. 27 mongod -- -- dbpath =.. /db1 --port=27018 --fork --syslog --replSet=kux 501 2125 10 10:24 am? 0:03. 09 mongod -- -- dbpath =.. / DB2 --port=27019 --fork --syslog --replSet=kux 501 2129 10 10:24 am? 0:02. 42 mongod -- -- dbpath =.. /db3 --port=27020 --fork --syslog --replSet=kux 501 2243 2208 0 10:36 am ttys000 0:00.00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn mongod 501 1514 470 0 10:03 am ttys008 0:10. 27 / Users/kux_testMac/soft/mongo/bin/mongod - f/Users/kux_testMac/soft/mongo/mongo. Conf Kux_testMac @ zyquan - 2: ~ / soft/mongo/bin | ⇒kill-9 2100 tail mongo localhost:27019 kux:PRIMARY> db.testfind()
{ "_id" : ObjectId("5eaa3965e5c7a96472a041ce"), "name" : "zyquan"."phonenumber" : "1866579xxxx" }
kux:PRIMARY> 
Copy the code

4.4 Authentication of Replica Set Authorization

4.4.1 keyfile certification

1.1 requirements

(1) When authenticating through the key file, each mongo instance in the replica set uses the contents of the key file as the shared password for authenticating with other members. Only Mongod instances with the correct key files can be added to the replica set.

(2) The contents of the key file must be between 6 and 1024 characters and must be the same for all members of the replica set.

1.2 create

You can generate the key file using any method you choose. For example, the following operations are used to generate a key file for OpenSSL.

openssl rand -base64 756 > ./keyfile
Copy the code

Major: The key must be base64 characters of 6 to 1024 characters. The key must have the same group permissions in Unix, but not in Windows.

1.3 Changing Permission

chmod 600 ./keyfile

1.4 Copy the key file to each server that hosts a replica set member. Ensure that the user running the Mongod instance is the owner of the file and has access to the key file.

4.4.2 Creating an administrator in the Primary Database

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

4.4.3 Restart the three databases in Auth mode

Kill the original three processes and restart the following services

mongod --dbpath=.. /db1 --port=27018 --fork --syslog --replSet=kux --keyFile=.. /keyfile --auth mongod --dbpath=.. /db2 --port=27019 --fork --syslog --replSet=kux --keyFile=.. /keyfile --auth mongod --dbpath=.. /db3 --port=27020 --fork --syslog --replSet=kux --keyFile=.. /keyfile --authCopy the code

4.4.4 test

Connect to the primary database and use db.auth(‘admin’, ‘admin’) to view the database

⇒ mongo localhost: 27018 mongo shell version v4.0.11 connecting to: mongo: / / localhost: 27018 /test? gssapiServiceName=mongodb Implicit session: session {"id" : UUID("cc18f704-fe07-465f-b0a8-91bd8b440086") }
MongoDB server version: 4.0.11
kux:PRIMARY> use admin
switched to db admin
kux:PRIMARY> show dbs
kux:PRIMARY> db.auth('admin'.'admin')
1
kux:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local0.000 GBtest0.000 GB kux: PRIMARY >Copy the code

Kill the master library, connect to the slave library, find that the slave library has automatically become the master library, we perform the same operation

⇒ mongo localhost: 27019 mongo shell version v4.0.11 connecting to: mongo: / / localhost: 27019 /test? gssapiServiceName=mongodb Implicit session: session {"id" : UUID("f86278d5-9c9b-485e-a4e2-8e24a0b9257e") }
MongoDB server version: 4.0.11
kux:PRIMARY> use admin
switched to db admin
kux:PRIMARY> show dbs
kux:PRIMARY> db.auth('admin'.'admin')
1
kux:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local0.000 GBtest0.000 GB kux: PRIMARY >Copy the code

5. Reference documents

  1. Mongoing.com/docs/introd…

  2. www.cnblogs.com/dbabd/p/108…

  3. Cloud.tencent.com/developer/a…

  4. The official documentation

  5. Mongoing.com/docs/core/s…

  6. www.ibm.com/developerwo…