顯示具有 mongodb 標籤的文章。 顯示所有文章
顯示具有 mongodb 標籤的文章。 顯示所有文章

init mongodb data in docker

 1. Given file in project folder ./mongo/docker-entrypoint-initdb.d:/initdb.sh

```

echo '=====================================>'

mongo --eval 'db.getSiblingDB("testqq").createUser({"user": "admin", "pwd": "admin", roles: [{"role": "readWrite","db": "testqq"}]});'

mongo --eval 'db.getSiblingDB("testqq").users.insert({"username" : "admin", "password" : "admin", "email" : "admin@gmail.com"});'

echo '<======================================'

```


2. Given docker-compose.yml

```

services:

  mongo:

    image: mongo:4.4

    ports:

      - "27017:27017"

    volumes:

    - "./mongo/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d"

```


3. Start docker-compose

```

$ docker-compose up

```


4. Check log, can find following log

```

mongo_1  | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/initdb.sh

mongo_1  | =====================================>

mongo_1  | MongoDB shell version v4.4.3

mongo_1  | connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.786+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:46062","connectionId":2,"connectionCount":1}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.787+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn2","msg":"client metadata","attr":{"remote":"127.0.0.1:46062","client":"conn2","doc":{"application":{"name":"MongoDB Shell"},"driver":{"name":"MongoDB Internal Client","version":"4.4.3"},"os":{"type":"Linux","name":"Ubuntu","architecture":"x86_64","version":"18.04"}}}}

mongo_1  | Implicit session: session { "id" : UUID("14d8434a-7c74-4509-a5de-d55a4c63bdf4") }

mongo_1  | MongoDB server version: 4.4.3

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.835+00:00"},"s":"I",  "c":"STORAGE",  "id":20320,   "ctx":"conn2","msg":"createCollection","attr":{"namespace":"admin.system.users","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"e8923719-dd5a-4a94-a417-bb32a7ca4ebc"}},"options":{}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.854+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn2","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"admin.system.users","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.854+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn2","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"admin.system.users","index":"user_1_db_1","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | Successfully added user: {

mongo_1  | "user" : "admin",

mongo_1  | "roles" : [

mongo_1  | {

mongo_1  | "role" : "readWrite",

mongo_1  | "db" : "testqq"

mongo_1  | }

mongo_1  | ]

mongo_1  | }

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.859+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn2","msg":"Connection ended","attr":{"remote":"127.0.0.1:46062","connectionId":2,"connectionCount":0}}

mongo_1  | MongoDB shell version v4.4.3

mongo_1  | connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.926+00:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:46064","connectionId":3,"connectionCount":1}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.927+00:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn3","msg":"client metadata","attr":{"remote":"127.0.0.1:46064","client":"conn3","doc":{"application":{"name":"MongoDB Shell"},"driver":{"name":"MongoDB Internal Client","version":"4.4.3"},"os":{"type":"Linux","name":"Ubuntu","architecture":"x86_64","version":"18.04"}}}}

mongo_1  | Implicit session: session { "id" : UUID("b0df77be-4789-4cb7-a1d0-6b64717b0207") }

mongo_1  | MongoDB server version: 4.4.3

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.937+00:00"},"s":"I",  "c":"STORAGE",  "id":20320,   "ctx":"conn3","msg":"createCollection","attr":{"namespace":"testqq.users","uuidDisposition":"generated","uuid":{"uuid":{"$uuid":"fb550551-8a86-4f98-9a93-b324e057084d"}},"options":{}}}

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.950+00:00"},"s":"I",  "c":"INDEX",    "id":20345,   "ctx":"conn3","msg":"Index build: done building","attr":{"buildUUID":null,"namespace":"testqq.users","index":"_id_","commitTimestamp":{"$timestamp":{"t":0,"i":0}}}}

mongo_1  | WriteResult({ "nInserted" : 1 })

mongo_1  | {"t":{"$date":"2021-01-25T16:48:42.957+00:00"},"s":"I",  "c":"NETWORK",  "id":22944,   "ctx":"conn3","msg":"Connection ended","attr":{"remote":"127.0.0.1:46064","connectionId":3,"connectionCount":0}}

mongo_1  | <======================================

```


5. Access mongo and check db

```

cds % docker exec -it cds_mongo_1 bash

root@186eb2a0f48d:/# mongo

MongoDB shell version v4.4.3

connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb

Implicit session: session { "id" : UUID("59729a8b-ecb1-439a-ab9f-63cc06f30e54") }

MongoDB server version: 4.4.3

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

https://docs.mongodb.com/

Questions? Try the MongoDB Developer Community Forums

https://community.mongodb.com

---

The server generated these startup warnings when booting:

        2021-01-25T16:52:03.600+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem

        2021-01-25T16:52:04.496+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted

---

---

        Enable MongoDB's free cloud-based monitoring service, which will then receive and display

        metrics about your deployment (disk utilization, CPU, operation statistics, etc).


        The monitoring data will be available on a MongoDB website with a unique URL accessible to you

        and anyone you share the URL with. MongoDB may use this information to make product

        improvements and to suggest MongoDB products and deployment options to you.


        To enable free monitoring, run the following command: db.enableFreeMonitoring()

        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()

---

> db.getSiblingDB('testqq').getUsers()

[

{

"_id" : "testqq.admin",

"userId" : UUID("886d3d0f-7457-4724-8ae6-d9494382bce4"),

"user" : "admin",

"db" : "testqq",

"roles" : [

{

"role" : "readWrite",

"db" : "testqq"

}

],

"mechanisms" : [

"SCRAM-SHA-1",

"SCRAM-SHA-256"

]

}

]

>

```

MongoDB config docker cluster

Start mongo and bind with interface
sudo docker run --name mongo1 -d -p 27017:27017 mongo --bind_ip_all --replSet rs1
sudo docker run --name mongo2 -d -p 27018:27017 mongo --bind_ip_all --replSet rs1
sudo docker run --name mongo3 -d -p 27019:27017 mongo --bind_ip_all --replSet rs1

Check ip address
mongo1 => 172.17.0.2
mongo2 => 172.17.0.3
mongo3 => 172.17.0.4
isaac@isaac-emachines-ET1870:~$ sudo docker inspect mongo1 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",
isaac@isaac-emachines-ET1870:~$ sudo docker inspect mongo2 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.3",
                    "IPAddress": "172.17.0.3",
isaac@isaac-emachines-ET1870:~$ sudo docker inspect mongo3 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.4",
                    "IPAddress": "172.17.0.4",

Install mongo client
sudo apt install mongodb-clients

Connect mongo client to port 27017
:~$ mongo --port 27017
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.4.1
WARNING: shell and server versions do not match
Server has startup warnings:
{"t":{"$date":"2020-10-29T10:41:36.684+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,  "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
{"t":{"$date":"2020-10-29T10:41:38.172+00:00"},"s":"W",  "c":"CONTROL",  "id":22120,  "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}

Show rs.status()
Notice replset config is not received
> rs.status()
{
        "operationTime" : Timestamp(0, 0),
        "ok" : 0,
        "errmsg" : "no replset config has been received",
        "code" : 94,
        "codeName" : "NotYetInitialized",
        "$clusterTime" : {
                "clusterTime" : Timestamp(0, 0),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        }
}

Prepare rsconfig
rsconf = {
    _id:"rs1",
    members:[
        {_id:0, host:"172.17.0.2:27017"},
        {_id:1, host:"172.17.0.3:27017"},
        {_id:2, host:"172.17.0.4:27017"},
    ]
}

Input to mongo-client and initiate replica set
> rsconf = {
...    _id:"rs1",
...    members:[
...        {_id:0, host:"172.17.0.2:27017"},
...        {_id:1, host:"172.17.0.3:27017"},
...        {_id:2, host:"172.17.0.4:27017"},
...    ]
... }
{
        "_id" : "rs1",
        "members" : [
                {
                        "_id" : 0,
                        "host" : "172.17.0.2:27017"
                },
                {
                        "_id" : 1,
                        "host" : "172.17.0.3:27017"
                },
                {
                        "_id" : 2,
                        "host" : "172.17.0.4:27017"
                }
        ]
}
> rs.initiate(rsconf)
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1603982247, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1603982247, 1)
}
rs1:SECONDARY>

Show members
rs1:PRIMARY> rs.status()
{
        "set" : "rs1",
        "date" : ISODate("2020-10-29T18:17:13.202Z"),
        "myState" : 1,
        "term" : NumberLong(1),
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 2,
        "writeMajorityCount" : 2,
        "votingMembersCount" : 3,
        "writableVotingMembersCount" : 3,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1603995431, 1),
                        "t" : NumberLong(1)
                },
                "lastCommittedWallTime" : ISODate("2020-10-29T18:17:11.315Z"),
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1603995431, 1),
                        "t" : NumberLong(1)
                },
                "readConcernMajorityWallTime" : ISODate("2020-10-29T18:17:11.315Z"),
                "appliedOpTime" : {
                        "ts" : Timestamp(1603995431, 1),
                        "t" : NumberLong(1)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1603995431, 1),
                        "t" : NumberLong(1)
                },
                "lastAppliedWallTime" : ISODate("2020-10-29T18:17:11.315Z"),
                "lastDurableWallTime" : ISODate("2020-10-29T18:17:11.315Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(1603995421, 1),
        "electionCandidateMetrics" : {
                "lastElectionReason" : "electionTimeout",
                "lastElectionDate" : ISODate("2020-10-29T14:37:39.776Z"),
                "electionTerm" : NumberLong(1),
                "lastCommittedOpTimeAtElection" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                },
                "lastSeenOpTimeAtElection" : {
                        "ts" : Timestamp(1603982247, 1),
                        "t" : NumberLong(-1)
                },
                "numVotesNeeded" : 2,
                "priorityAtElection" : 1,
                "electionTimeoutMillis" : NumberLong(10000),
                "numCatchUpOps" : NumberLong(0),
                "newTermStartDate" : ISODate("2020-10-29T14:37:40.542Z"),
                "wMajorityWriteAvailabilityDate" : ISODate("2020-10-29T14:37:42.121Z")
        },
        "members" : [
                {
                        "_id" : 0,
                        "name" : "172.17.0.2:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 27337,
                        "optime" : {
                                "ts" : Timestamp(1603995431, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-10-29T18:17:11Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1603982259, 1),
                        "electionDate" : ISODate("2020-10-29T14:37:39Z"),
                        "configVersion" : 1,
                        "configTerm" : 1,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                },
                {
                        "_id" : 1,
                        "name" : "172.17.0.3:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 13185,
                        "optime" : {
                                "ts" : Timestamp(1603995431, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1603995431, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-10-29T18:17:11Z"),
                        "optimeDurableDate" : ISODate("2020-10-29T18:17:11Z"),
                        "lastHeartbeat" : ISODate("2020-10-29T18:17:12.066Z"),
                        "lastHeartbeatRecv" : ISODate("2020-10-29T18:17:13.100Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "172.17.0.2:27017",
                        "syncSourceId" : 0,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 1
                },
                {
                        "_id" : 2,
                        "name" : "172.17.0.4:27017",
                        "health" : 1,
                        "state" : 2,
                        "stateStr" : "SECONDARY",
                        "uptime" : 13185,
                        "optime" : {
                                "ts" : Timestamp(1603995431, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDurable" : {
                                "ts" : Timestamp(1603995431, 1),
                                "t" : NumberLong(1)
                        },
                        "optimeDate" : ISODate("2020-10-29T18:17:11Z"),
                        "optimeDurableDate" : ISODate("2020-10-29T18:17:11Z"),
                        "lastHeartbeat" : ISODate("2020-10-29T18:17:12.042Z"),
                        "lastHeartbeatRecv" : ISODate("2020-10-29T18:17:13.134Z"),
                        "pingMs" : NumberLong(0),
                        "lastHeartbeatMessage" : "",
                        "syncSourceHost" : "172.17.0.2:27017",
                        "syncSourceId" : 0,
                        "infoMessage" : "",
                        "configVersion" : 1,
                        "configTerm" : 1
                }
        ],
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1603995431, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1603995431, 1)
}

Insert 1000 records
rs1:PRIMARY> use test
switched to db test
rs1:PRIMARY> for (i=0; i<1000; i++) {db.coll.insert({count:1})}
WriteResult({ "nInserted" : 1 })
rs1:PRIMARY> db.coll.count()
1000

Check isMaster
rs1:PRIMARY> db.isMaster()
{
        "topologyVersion" : {
                "processId" : ObjectId("5f9a9c60e604cb72e52ff28e"),
                "counter" : NumberLong(6)
        },
        "hosts" : [
                "172.17.0.2:27017",
                "172.17.0.3:27017",
                "172.17.0.4:27017"
        ],
        "setName" : "rs1",
        "setVersion" : 1,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "172.17.0.2:27017",
        "me" : "172.17.0.2:27017",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
                "opTime" : {
                        "ts" : Timestamp(1604044322, 1),
                        "t" : NumberLong(1)
                },
                "lastWriteDate" : ISODate("2020-10-30T07:52:02Z"),
                "majorityOpTime" : {
                        "ts" : Timestamp(1604044322, 1),
                        "t" : NumberLong(1)
                },
                "majorityWriteDate" : ISODate("2020-10-30T07:52:02Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2020-10-30T07:52:11.864Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "connectionId" : 33,
        "minWireVersion" : 0,
        "maxWireVersion" : 9,
        "readOnly" : false,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604044322, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604044322, 1)
}

Connect to master DB and query will success
~$ mongo --port 27019
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27019/
MongoDB server version: 4.4.1
WARNING: shell and server versions do not match
Server has startup warnings:
{"t":{"$date":"2020-10-29T10:41:49.380+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,  "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
{"t":{"$date":"2020-10-29T10:41:51.036+00:00"},"s":"W",  "c":"CONTROL",  "id":22120,  "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}
rs1:SECONDARY> conn1 = new Mongo("172.17.0.2:27017")
connection to 172.17.0.2:27017

rs1:SECONDARY> db1 = conn1.getDB("test")
test

rs1:SECONDARY> db1.coll.find()
{ "_id" : ObjectId("5f9bc53af256e53d936e29bb"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29bc"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29bd"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29be"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29bf"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c0"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c1"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c2"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c3"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c4"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c5"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c6"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c7"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c8"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c9"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29ca"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29cb"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29cc"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29cd"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29ce"), "count" : 1 }

Connect to secondary DB
Secondaries will refuce read request by default
~$ mongo --port 27019
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27019/
MongoDB server version: 4.4.1
WARNING: shell and server versions do not match
Server has startup warnings:
{"t":{"$date":"2020-10-29T10:41:49.380+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,  "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
{"t":{"$date":"2020-10-29T10:41:51.036+00:00"},"s":"W",  "c":"CONTROL",  "id":22120,  "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}


rs1:SECONDARY> conn2 = new Mongo("172.17.0.3:27017")
connection to 172.17.0.3:27017

rs1:SECONDARY> db2 = conn2.getDB("test")
test

rs1:SECONDARY> db2.coll.find()
Error: error: {
        "topologyVersion" : {
                "processId" : ObjectId("5f9a9c67f63d0c64a80a5bd0"),
                "counter" : NumberLong(4)
        },
        "operationTime" : Timestamp(1604045052, 1),
        "ok" : 0,
        "errmsg" : "not master and slaveOk=false",
        "code" : 13435,
        "codeName" : "NotMasterNoSlaveOk",
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604045052, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        }
}

Allow read from secondaries by setSlaveOk()
rs1:SECONDARY> conn2.setSlaveOk()
rs1:SECONDARY> db2.coll.find()
{ "_id" : ObjectId("5f9bc53af256e53d936e29bb"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29bc"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29bd"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29cb"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29c5"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29d7"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e29f5"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a06"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a0a"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a33"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a3f"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a48"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a54"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a6a"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53af256e53d936e2a80"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53bf256e53d936e2ac3"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53bf256e53d936e2ad4"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53bf256e53d936e2ad6"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53bf256e53d936e2af9"), "count" : 1 }
{ "_id" : ObjectId("5f9bc53bf256e53d936e2aff"), "count" : 1 }
Type "it" for more

Write on secondary will fail
Secondaries will get write only through replication from master
rs1:SECONDARY> db2.coll.insert({"count":1001})
WriteResult({ "writeError" : { "code" : 10107, "errmsg" : "not master" } })

If primary goes down, one of the secondaries will automatically be elected primary.

Remove and add node
// connect primary
~$ mongo --port 27017
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017/
MongoDB server version: 4.4.1
WARNING: shell and server versions do not match
Server has startup warnings:
{"t":{"$date":"2020-10-29T10:41:36.684+00:00"},"s":"I",  "c":"STORAGE",  "id":22297,  "ctx":"initandlisten","msg":"Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem","tags":["startupWarnings"]}
{"t":{"$date":"2020-10-29T10:41:38.172+00:00"},"s":"W",  "c":"CONTROL",  "id":22120,  "ctx":"initandlisten","msg":"Access control is not enabled for the database. Read and write access to data and configuration is unrestricted","tags":["startupWarnings"]}
rs1:PRIMARY>

// check primary and secondaries
rs1:PRIMARY> rs.isMaster()
{
        "topologyVersion" : {
                "processId" : ObjectId("5f9a9c60e604cb72e52ff28e"),
                "counter" : NumberLong(6)
        },
        "hosts" : [
                "172.17.0.2:27017",
                "172.17.0.3:27017",
                "172.17.0.4:27017"
        ],
        "setName" : "rs1",
        "setVersion" : 1,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "172.17.0.2:27017",
        "me" : "172.17.0.2:27017",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
                "opTime" : {
                        "ts" : Timestamp(1604047942, 1),
                        "t" : NumberLong(1)
                },
                "lastWriteDate" : ISODate("2020-10-30T08:52:22Z"),
                "majorityOpTime" : {
                        "ts" : Timestamp(1604047942, 1),
                        "t" : NumberLong(1)
                },
                "majorityWriteDate" : ISODate("2020-10-30T08:52:22Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2020-10-30T08:52:27.262Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "connectionId" : 36,
        "minWireVersion" : 0,
        "maxWireVersion" : 9,
        "readOnly" : false,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604047942, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604047942, 1)
}

// remove secondary node: 172.17.0.3:27017
rs1:PRIMARY> rs.remove("172.17.0.3:27017")
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604048022, 2),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604048022, 2)
}

// check isMaster
rs1:PRIMARY> rs.isMaster()
{
        "topologyVersion" : {
                "processId" : ObjectId("5f9a9c60e604cb72e52ff28e"),
                "counter" : NumberLong(7)
        },
        "hosts" : [
                "172.17.0.2:27017",
                "172.17.0.4:27017"
        ],
        "setName" : "rs1",
        "setVersion" : 2,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "172.17.0.2:27017",
        "me" : "172.17.0.2:27017",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
                "opTime" : {
                        "ts" : Timestamp(1604048062, 1),
                        "t" : NumberLong(1)
                },
                "lastWriteDate" : ISODate("2020-10-30T08:54:22Z"),
                "majorityOpTime" : {
                        "ts" : Timestamp(1604048062, 1),
                        "t" : NumberLong(1)
                },
                "majorityWriteDate" : ISODate("2020-10-30T08:54:22Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2020-10-30T08:54:24.595Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "connectionId" : 36,
        "minWireVersion" : 0,
        "maxWireVersion" : 9,
        "readOnly" : false,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604048062, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604048062, 1)
}

// add node back
rs1:PRIMARY> rs.add("172.17.0.3:27017")
{
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604048096, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604048096, 1)
}

// check isMaster
rs1:PRIMARY> rs.isMaster()
{
        "topologyVersion" : {
                "processId" : ObjectId("5f9a9c60e604cb72e52ff28e"),
                "counter" : NumberLong(8)
        },
        "hosts" : [
                "172.17.0.2:27017",
                "172.17.0.4:27017",
                "172.17.0.3:27017"
        ],
        "setName" : "rs1",
        "setVersion" : 3,
        "ismaster" : true,
        "secondary" : false,
        "primary" : "172.17.0.2:27017",
        "me" : "172.17.0.2:27017",
        "electionId" : ObjectId("7fffffff0000000000000001"),
        "lastWrite" : {
                "opTime" : {
                        "ts" : Timestamp(1604048112, 1),
                        "t" : NumberLong(1)
                },
                "lastWriteDate" : ISODate("2020-10-30T08:55:12Z"),
                "majorityOpTime" : {
                        "ts" : Timestamp(1604048112, 1),
                        "t" : NumberLong(1)
                },
                "majorityWriteDate" : ISODate("2020-10-30T08:55:12Z")
        },
        "maxBsonObjectSize" : 16777216,
        "maxMessageSizeBytes" : 48000000,
        "maxWriteBatchSize" : 100000,
        "localTime" : ISODate("2020-10-30T08:55:14.066Z"),
        "logicalSessionTimeoutMinutes" : 30,
        "connectionId" : 36,
        "minWireVersion" : 0,
        "maxWireVersion" : 9,
        "readOnly" : false,
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1604048112, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1604048112, 1)
}

Check config by rs.config()
rs1:PRIMARY> rs.config()
{
        "_id" : "rs1",
        "version" : 3,
        "term" : 1,
        "protocolVersion" : NumberLong(1),
        "writeConcernMajorityJournalDefault" : true,
        "members" : [
                {
                        "_id" : 0,
                        "host" : "172.17.0.2:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 2,
                        "host" : "172.17.0.4:27017",
                        "arbiterOnly" : false,
                        "buildIndexes" : true,
                        "hidden" : false,
                        "priority" : 1,
                        "tags" : {

                        },
                        "slaveDelay" : NumberLong(0),
                        "votes" : 1
                },
                {
                        "_id" : 3,
                        "host" : "172.17.0.3:27017",
                        "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("5f9ad3a6e604cb72e52ff2f2")
        }
}

Other commands
  • Modify config: rs.reconfig

別名演算法 Alias Method

 題目 每個伺服器支援不同的 TPM (transaction per minute) 當 request 來的時候, 系統需要馬上根據 TPM 的能力隨機找到一個適合的 server. 雖然稱為 "隨機", 但還是需要有 TPM 作為權重. 解法 別名演算法...