Overview概述
In this guide, you can learn how to use the Node.js driver to configure read and write operations.在本指南中,您可以学习如何使用Node.js驱动程序配置读写操作。
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:要了解有关读写设置的更多信息,请参阅MongoDB Server手册中的以下指南:
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:MongoClientOptions对象传递给构造函数来设置MongoClient实例的读取首选项、读取关注和写入关注。该代码配置了以下设置:
SECONDARYread preference: Read operations retrieve data from secondary replica set members读取首选项:读取操作从辅助副本集成员检索数据localread 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 members读取关注:读取操作返回实例的最新数据,但不保证数据已写入大多数副本集成员2write 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 或者,您可以在连接URI中指定读写设置,该URI作为参数传递给MongoClient constructor:MongoClient构造函数:
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:TransactionOptions对象传递给startTransaction()方法来设置事务的读取首选项、读取关注和写入关注。该代码配置了以下设置:
PRIMARYread preference: Read operations retrieve data from the primary replica set member读取首选项:读取操作从主副本集成员检索数据majorityread concern: Read operations return the instance's most recent data that has been written to a majority of replica set members读取关注:读取操作返回已写入大多数副本集成员的实例的最新数据1write 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:DbOptions对象传递给db()方法来设置名为test_database的数据库的读取首选项、读取关注和写入关注。该代码配置了以下设置:
PRIMARY_PREFERREDread preference: Read operations retrieve data from the primary replica set member, or secondary members if the primary is unavailable读取首选项:读取操作从主副本集成员或辅助成员(如果主副本不可用)检索数据availableread 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 members读取关注:读取操作返回实例的最新数据,但不保证数据已写入大多数副本集成员majoritywrite 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:CollectionOptions对象传递给collection()方法来设置名为test_collection的集合的读取首选项、读取关注和写入关注。该代码配置了以下设置:
SECONDARY_PREFERREDread preference: Read operations retrieve data from secondary replica set members, or the primary members if no secondaries are available读取首选项:读取操作从辅助副本集成员检索数据,如果没有辅助副本集可用,则从主成员检索数据availableread 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 members读取关注:读取操作返回实例的最新数据,但不保证数据已写入大多数副本集成员0write 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.在MongoDB Server中,您可以根据您选择的任何条件将键值标签应用于副本集成员。然后,您可以使用这些标记来定位一个或多个成员进行读取操作。
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.默认情况下,Node.js驱动程序在选择要读取的成员时忽略标签。要指示Node.js驱动程序更喜欢某些标签,请将它们作为参数传递给read preference类构造函数。
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:readPreference选项设置为一个标记集,该标记集指示test_database按以下顺序优先从辅助副本集成员读取:
Members from the New York data center (来自纽约数据中心的成员({ dc: 'ny' }){ dc: 'ny' })Members from the San Francisco data center (旧金山数据中心的成员({ dc: 'sf' }){ dc: 'sf' })Any secondary members (任何secondary成员({}){})
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.如果多个副本集成员与您指定的读取首选项和标记集匹配,Node.js驱动程序将根据最近的副本集成员的ping时间进行读取。
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 默认情况下,驱动程序仅使用ping时间在最近成员15毫秒以内的成员进行查询。要在延迟较高的成员之间分配读取,请将localThresholdMS option to the MongoClient() constructor.localThresholdMS选项传递给MongoClient()构造函数。
The following example specifies a local threshold of 35 milliseconds:以下示例指定了35毫秒的本地阈值:
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.在前面的示例中,Node.js驱动程序在最接近成员的ping时间的35毫秒内将读取分配给匹配的成员。
Note
The Node.js driver ignores the value of Node.js驱动程序在通过localThresholdMS when communicating with a replica set through a mongos instance. mongos实例与副本集通信时忽略localThresholdMS的值。In this case, use the localThreshold command-line option.在这种情况下,使用localThreshold命令行选项。
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.默认情况下,MongoDB使用二进制排序规则对字符串进行排序。此默认排序规则使用ASCII标准字符值来比较和排序字符串。语言和地区具有不同于ASCII标准的特定字符排序约定,您可以选择对操作应用一组不同的排序规则。
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. collation选项时,必须指定locale字段。所有其他字段都是可选的。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.locale字段默认值的完整列表,请参阅MongoDB服务器手册中的支持的语言和区域设置。
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.collation对象,并将其locale字段设置为要使用的语言排序规则。然后,将此对象作为选项参数传递给与目标排序规则级别对应的方法。
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:names的新集合,并将其默认排序规则设置为"fr_CA"区域设置:
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:names集合上创建一个索引,指定不同的排序规则,如下例所示:
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.names集合运行操作,该操作将覆盖默认排序规则。
The names collection contains the following documents:names集合包含以下文档:
{ "_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:findOneAndUpdate()方法来更新第一个first_name值为"Gunter"的匹配文档。该代码应用了"de"区域设置和"phonebook"区域设置变量的排序规则:
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. phonebook(电话簿)区域设置变体指示驱动程序将有变音的字符排序在没有变音的相同字符之前。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:first_name值为"Günter"的文档与变音匹配,并返回以下更新信息:
{ 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.要了解有关区域设置变体的更多信息,请参阅MongoDB服务器手册中的本地变体。
API Documentation文档
To learn more about any of the methods or types discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何方法或类型的更多信息,请参阅以下API文档: