Lesson 5: Read and Write Concerns with MongoDB Deployments / Learn

Code Summary: Read and Write Concerns with MongoDB Deployments

Review the following code, which demonstrates how to:

  • Specify the write concern on an individual operation
  • Set the default read and write concerns
  • Set the read preference in the connection string

Specify the Write Concern on an Individual Operation

The following code shows how to specify the write concern on an operation.

Use insertOne() to insert a document into a collection. Within the parentheses of insertOne(), include two documents: one that contains the document data, and one that specifies the write concern. In the following example, the second document sets the write concern to "majority" and the write timeout to 3000 milliseconds:

db.cats.insertOne({ name: "Mac", color: "black", age: 6 }, { writeConcern:
{ w: "majority" , wtimeout: 3000 } });

Set the Default Read and Write Concerns

The following code shows how to set the default read and write concerns.

Use the adminCommand() to issue a command against the admin database. This command accepts a document. In this example, the document contains defaultRWConcern, which is set to 1 and specifies the command that’s being executed.

Next, set the defaultReadConcern level to "majority", which returns only data that has been acknowledged as written to a majority of members in a replica set.

Finally, set the defaultWriteConcern level to "majority" so that a majority of members must acknowledge the write operation.

db.adminCommand({
    setDefaultRWConcern : 1,
    defaultReadConcern: { level : "majority" },
    defaultWriteConcern: { w: "majority" }
  })

Set the Read Preference

To set the read preference, append it to the options in the connection string. In this example, we’re reading from the secondary. Additionally, we can set the time limit for how stale our data can be.

mongodb://db0.example.com,db1.example.com,db2.example.com/?replicaSet=myRepl&readPreference=secondary&maxStalenessSeconds=120