Configure CRUD Operations
On this page
Overview
In this guide, you can learn how to use the Node.js driver to configure read and write operations.
Read and Write Settings
You can control how the driver routes read operations by setting a read preference. You can also control how the driver handles data consistency and durability by setting a read concern or write concern. Read concerns specify the level of durability required for the data when performing read operations, and write concerns specify how the driver waits for acknowledgment of write operations on a replica set.
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
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.
Tip
To learn more about the read and write settings, see the following guides in the MongoDB Server manual:
This section shows how to configure your read and write settings at each level.
Client Configuration
This example shows how to set the read preference, read concern, and
write concern of a MongoClient
instance by passing a MongoClientOptions
object to the constructor. The code configures the following settings:
SECONDARY
read preference: Read operations retrieve data from secondary replica set memberslocal
read concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set members2
write concern: The primary and one secondary replica set member must acknowledge the write operation
const clientOptions = { readPreference: ReadPreference.SECONDARY, readConcern: { level: "local" }, writeConcern: { w: 2 }, }; const client = new MongoClient("mongodb://localhost:27017", clientOptions);
Alternatively, you can specify the read and write settings in the connection
URI, which is passed as a parameter to the MongoClient
constructor:
const uri = "mongodb://localhost:27017/?readPreference=secondary&readConcernLevel=local&w=2"; const clientWithUri = new MongoClient(uri);
Transaction Configuration
This example shows how to set the read preference, read concern, and
write concern of a transaction by passing a TransactionOptions
object
to the startTransaction()
method. The code configures the following settings:
PRIMARY
read preference: Read operations retrieve data from the primary replica set membermajority
read concern: Read operations return the instance's most recent data that has been written to a majority of replica set members1
write concern: The primary replica set member must acknowledge the write operation
const transactionOptions = { readPreference: ReadPreference.PRIMARY, readConcern: { level: "majority" }, writeConcern: { w: 1 }, }; const session = client.startSession(); session.startTransaction(transactionOptions);
Database Configuration
This example shows how to set the read preference, read concern, and
write concern of a database called test_database
by passing a DbOptions
object to the db()
method. The code configures the following settings:
PRIMARY_PREFERRED
read preference: Read operations retrieve data from the primary replica set member, or secondary members if the primary is unavailableavailable
read concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set membersmajority
write concern: The majority of all replica set members must acknowledge the write operation
const dbOptions = { readPreference: ReadPreference.PRIMARY_PREFERRED, readConcern: { level: "available" }, writeConcern: { w: "majority" }, }; const db = client.db("test_database", dbOptions);
Collection Configuration
This example shows how to set the read preference, read concern, and
write concern of a collection called test_collection
by passing a CollectionOptions
object to the collection()
method. The code configures the following settings:
SECONDARY_PREFERRED
read preference: Read operations retrieve data from secondary replica set members, or the primary members if no secondaries are availableavailable
read concern: Read operations return the instance's most recent data without guaranteeing that the data has been written to a majority of the replica set members0
write concern: Does not request acknowledgment of the write operation
const collOptions = { readPreference: ReadPreference.SECONDARY_PREFERRED, readConcern: { level: "available" }, writeConcern: { w: 0 }, }; const collection = db.collection("test_collection", collOptions);
Tag Sets
In MongoDB Server, you can apply key-value tags to replica-set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.
By default, the Node.js driver ignores tags when choosing a member to read from. To instruct the Node.js driver to prefer certain tags, pass them as a parameter to your read preference class constructor.
This code example sets the readPreference
option to a tag set that
instructs test_database
to prefer reads from secondary replica set
members in the following order:
Members from the New York data center (
{ dc: 'ny' }
)Members from the San Francisco data center (
{ dc: 'sf' }
)Any secondary members (
{}
)
const taggedReadPreference = new ReadPreference( ReadPreference.SECONDARY, [ { dc: "ny" }, { dc: "sf" }, {} ] ); const dbWithTags = client.db( "test_database", { readPreference: taggedReadPreference } );
Local Threshold
If multiple replica-set members match the read preference and tag sets you specify, the Node.js driver reads from the nearest replica set members, chosen according to their ping time.
By default, the driver uses only those members whose ping times are within 15 milliseconds
of the nearest member for queries. To distribute reads between members with
higher latencies, pass the localThresholdMS
option to the MongoClient()
constructor.
The following example specifies a local threshold of 35 milliseconds:
const clientWithLocalThreshold = new MongoClient("mongodb://localhost:27017", { replicaSet: "repl0", readPreference: ReadPreference.SECONDARY_PREFERRED, localThresholdMS: 35 });
In the preceding example, the Node.js driver distributes reads between matching members within 35 milliseconds of the closest member's ping time.
Note
The Node.js driver ignores the value of localThresholdMS
when communicating with a
replica set through a mongos
instance. In this case, use the
localThreshold
command-line option.
Collation
You can specify a collation to modify the behavior of read and write operations. A collation is a set of language-specific rules for string comparison, such as for letter case and accent marks.
MongoDB sorts strings using binary collation by default. This default collation uses the ASCII standard character values to compare and order strings. Languages and locales have specific character ordering conventions that differ from the ASCII standard, and you can choose to apply a different set of collation rules to your operation.
You can specify a collation at the following levels:
Collection: Sets the default collation for operations on the collection. You cannot define a collation for an existing collection.
Index: Sets the collation for operations that use the index.
Operation: Sets the operation's collation and overrides any inherited collations.
Collation Fields
The collation object contains the following fields:
collation: { locale: <string>, caseLevel: <bool>, caseFirst: <string>, strength: <int>, numericOrdering: <bool>, alternate: <string>, maxVariable: <string>, backwards: <bool> }
When setting the collation
option, you must specify the locale
field.
All other fields are optional. For a complete list of supported locales and the default values
for the locale
fields, see Supported Languages and Locales
in the MongoDB Server manual.
Collation Examples
To specify a collation, create a collation
object and set its
locale
field to the language collation you want to use. Then,
pass this object as an options parameter to the method corresponding
to the target collation level.
This section includes examples that set collations at the collection, index, and operation levels.
Set Collection and Index Collations
The following example creates a new collection named names
and sets its default collation to the "fr_CA"
locale:
const db = client.db("db") db.createCollection("names", { collation: { locale: "fr_CA" }, });
You can create an index on the names
collection that specifies a different
collation, as shown in the following example:
const coll = db.collection("names"); coll.createIndex( { "last_name" : 1 }, { "collation" : { "locale" : "en_US" } });
Set an Operation Collation
You can run an operation on the names
collection, created in
the preceding section, that overrides
the default collation.
The names
collection contains the following documents:
{ "_id" : 1, "first_name" : "Hans", "last_name" : "Muller" } { "_id" : 2, "first_name" : "Gunter", "last_name" : "Braun" } { "_id" : 3, "first_name" : "Günter", "last_name" : "Krause" } { "_id" : 4, "first_name" : "Jürgen", "last_name" : "Weber" }
This example calls the findOneAndUpdate()
method to update
the first matching document that has a first_name
value of "Gunter"
.
The code applies a collation with the "de"
locale and the "phonebook"
locale variant:
coll.findOneAndUpdate( { first_name: { $lt: "Gunter" } }, { $set: { verified: true } }, { collation: { locale: "de@collation=phonebook" } }, );
In the preceding example, the phonebook
locale variant instructs
the driver to sort characters with umlauts before the same characters without
umlauts. As a result, the operation matches the document that has
a first_name
value of "Günter"
, with an umlaut, and returns
the following update information:
{ lastErrorObject: { updatedExisting: true, n: 1 }, value: { _id: 3, first_name: 'Günter', last_name: 'Krause' }, ok: 1 }
Tip
To learn more about locale variants, see Local Variants in the MongoDB Server manual.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: