定义
Mongo.startSession(<options>)Starts a session for the connection.
mongoshassigns the session ID to commands associated with the session.重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for database commands or language-specific drivers, such as Node.js.有关数据库命令,请参阅
startSession命令。如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
会话只能与创建会话的
MongoClient对象一起使用。单个会话不能同时使用。使用单个会话的操作必须按顺序运行。The
startSession()method can take a document with session options. The options available are:字段说明因果一致性(Causal Consistency)
Boolean. Enables or disables causal consistency for the session.
Mongo.startSession()enablescausalConsistencyby default. Mutually exclusive withsnapshot.启动会话后,无法修改其
causalConsistency设置。即使
Mongo()连接对象禁用了因果一致性,会话仍可能启用了因果一致性,反之亦然。要设置连接对象的因果一致性,请参见Mongo.setCausalConsistency()。事务外的
文档。指定读关注。
要在启动会话后修改设置,请参阅
Session.getOptions().setReadConcern()。readPreference
文档。指定读取偏好。
readPreference 文档包含
mode字段和可选的tags字段:{ mode: <string>, tags: <array> } 要在启动会话后修改设置,请参阅
Session.getOptions().setReadPreference()。retryWrites
布尔值。启用或禁用遇到瞬时网络错误时重试写入的功能。
If you start
mongoshwith the--retryWritesoption,retryWritesis enabled by default forMongo.startSession().启动会话后,无法修改其
retryWrites设置。snapshot
布尔值。 为MongoDB 5.0 + 部署启用会话快照读取。 与
causalConsistency互斥。writeConcern
文档。指定写关注。
要在启动会话后修改设置,请参阅
Session.getOptions().setWriteConcern()。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
示例
The following starts a session with causal consistency and retryable writes enabled on the Mongo() connection object associated with mongosh's global db variable:
db = db.getMongo().startSession({retryWrites: true, causalConsistency: true}).getDatabase(db.getName());