The DDS instance uses multiple replicas to store data, where one replica's role is primary to accept data writes and the other nodes synchronize data changes via oplog.
If the primary node crashes after successfully writing data, but the data has not yet been synchronized by other secondary nodes. At this point, the background re-elects a normal secondary node as the new primary node, but this new primary node does not contain the latest written data. The original primary node becomes a secondary node after being repaired and rejoined in the replica set, and the newly written data will be rollback.
In order to avoid the situation where the primary node crashes unexpectedly and some of the data is rolled back, you can specify write concern to set the write level and the number of nodes to which the data is successfully replicated before it is returned.
The format specified by write concern is as follows:
{ w: <value>, j: <boolean>, wtimeout: <number> }Where w specifies how many mongod nodes the data is successfully replicated to before the results are returned to the client (including the primary node itself). Common configurations include:
number. Such as 0 and 1.
"majority". The server automatically calculates the number of most nodes in the replica set based on the current number of nodes with voting rights. For example, in a replica set of 3 mongod nodes, if each mongod node has voting rights by default, the number of "major" nodes is 2.
Parameter j indicates whether the journal is written in the background and then returns successfully, which can be specified as true or false. If w specifies "major", then j defaults to true.
wtimeout indicates the execution timeout of the operation, in milliseconds, which takes effect when w is greater than 1.
For nodes with 3 replicas, it is recommended that w be specified as "majority" and wtimeout be specified based on actual business needs. In this way, partial data loss after an unexpected downtime of the master node can be avoided, and better availability can be achieved. The following is an example:
db.coll.insert({a:1}, {writeConcern: {w: "majority", wtimeout: 1000}})