CRUD Operations on Replica Sets
On this page
- Overview
- Write Concern
- Example: Set the Write Concern for a Single Write Operation
- Example: Retrieve and Apply an Existing Write Concern
- Read Concern
- Example: Set the Read Concern Level of an Aggregation
- Example: Change the Read Concern of a Database
- Read Preference
- Example: Set Read Preference and Concerns for a Transaction
- Example: Set the Read Preference of a Cluster in the Connection String
- API Documentation
Overview
In this guide, you can learn how to use the write concern, read concern, and read preference configurations to modify the way that MongoDB runs create, read, update, and delete (CRUD) operations on replica sets.
You can set write concern, read concern, and read preference options at the following levels:
Client, which sets the default for all operation executions unless overridden
Session
Transaction
Database
Collection
The preceding list also indicates the increasing order of precedence of the option settings. For example, if you set a read concern level for a transaction, it will override a read concern level set for the client.
These options allow you to customize the causal consistency and availability of the data in your replica sets.
Write Concern
The write concern specifies the level of acknowledgement requested from MongoDB for write operations, such as an insert or update, before the operation successfully returns. Operations that do not specify an explicit write concern inherit the global default write concern settings.
For more information, see Write Concern in the MongoDB Server manual. For detailed API documentation, see the Write Concern API documentation.
The following table describes the write_concern
parameters:
Parameter | Type | Description |
---|---|---|
| integer or string | Requests acknowledgment that the write operation has propagated to a specified
number of |
| integer | Specifies a time limit to prevent write operations from blocking indefinitely. |
| boolean | Requests acknowledgment that the write operation has been written to the on-disk journal. |
Example: Set the Write Concern for a Single Write Operation
The following code creates a new document and specifies the w
and wtimeout
write concern settings:
client = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'myDB') myDB = client.database myCollection = myDB[:myCollection] myCollection.insert_one( { name: 'anotherDocumentName' }, write: { w: 2, wtimeout: 5000 } )
Example: Retrieve and Apply an Existing Write Concern
The following code uses the new_write_concern
method to construct a write_concern
from the options of an existing database reference, myDB
. Then the new
write concern is applied to an inserted document.
myDoc = { name: 'New Document' } new_write_concern = Mongo::WriteConcern.get(myDB.write_concern) myDB[:myCollection].with(write: new_write_concern).insert_one(myDoc)
Note
myDB
can be replaced with a reference to any entity that accepts a write concern option.
Read Concern
The read concern specifies the following behaviors:
Level of causal consistency across replica sets
Isolation guarantees maintained during a query
You can specify the read concern setting by using the level
parameter. The default
read concern level is local
. This means that the client returns the data from the
replica set member that the client is connected to, with no guarantee that the data has
been written to all replica set members.
Note
Lower read concern level requirements may reduce latency.
For more information about read concerns or read concern levels, see
Read Concern in the MongoDB Server manual. For more
detail on the read_concern
type and definitions of the read concern levels, see
Read Concern
in the API documentation.
Example: Set the Read Concern Level of an Aggregation
The following code sets the read concern level of an aggregation to "available"
:
pipeline = [ { "$match" => { category: 'KITCHENWARE' } }, { "$unset" => ['_id', 'category'] } ] result = myCollection.aggregate(pipeline, read: { read_concern: { level: :available } })
Tip
To learn more about aggregation operations, see the Transform Your Data with Aggregation guide.
Example: Change the Read Concern of a Database
The following code changes the read concern level of a database to "local"
:
client = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'mydb', read_concern: { level: :local }) myDB = client.database
Read Preference
The read preference determines which member of a replica set MongoDB reads when running a query.
For more detailed API documentation, see the Read Preference API documentation.
The following table shows options you can use to customize how the server evaluates members:
Parameter | Type | Description |
---|---|---|
|
| Specifies a requirement or preference for which replica set
member the server reads from. The default mode, |
|
| Assigns tags to secondary replica set members to customize how the server evaluates
them. Tags cannot be used with the |
|
| Sets various options, including hedge and maxStalenessSeconds that can be applied to your read preference. |
Example: Set Read Preference and Concerns for a Transaction
The following code sets the read preference, read concern, and write concern for the operations in a transaction:
transaction_options = { read: { mode: :primary }, read_concern: { level: :local }, write_concern: { w: :majority } } session = client.start_session session.start_transaction(transaction_options) session.commit_transaction # ... rescue => e session.abort_transaction puts "Transaction aborted due to an error: #{e.message}" ensure session.end_session end
Tip
To learn more about transactions, see the Transactions guide.
Example: Set the Read Preference of a Cluster in the Connection String
This code example creates a MongoClient
that uses the secondary
read
preference mode when performing queries on a cluster:
uri = 'mongodb+srv://<user>:<password>@<cluster-url>' options = { read: { mode: :secondary, max_staleness: 120 } } client = Mongo::Client.new(uri, options) myDB = client.database
The preceding example also sets the maxStalenessSeconds
option to 120
.
For more information about connection string options, see the Connection String Options
section in the MongoDB Server manual.
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation: