- MongoDB官方文档中文版
- MongoDB用户手册
- MongoDB简介
- 安装 MongoDB
- 安装MongoDB社区版
- 安装MongoDB企业版
- 将社区版MongoDB升级到企业版MongoDB
- 验证MongoDB软件包的完整性
- Mongo Shell
- 增删改查操作
- 聚合
- 数据模式
- 数据建模介绍
- 模式验证
- Data Modeling Concepts
- Data Model Examples and Patterns
- Model Relationships Between Documents
- Model One-to-One Relationships with Embedded Documents
- Model One-to-Many Relationships with Embedded Documents
- Model One-to-Many Relationships with Document References
- Model Tree Structures
- Model Tree Structures with Parent References
- Model Tree Structures with Child References
- Model Tree Structures with an Array of Ancestors
- Model Tree Structures with Materialized Paths
- Model Tree Structures with Nested Sets
- Model Specific Application Contexts
- Model Data for Atomic Operations
- Model Data to Support Keyword Search
- Model Data for Schema Versioning
- Model Monetary Data
- Model Time Data
- Model Computed Data
- Data Model Reference
- 事务
- 索引
- Single Field Indexes
- Compound Indexes
- Multikey Indexes
- Text Indexes
- Wildcard Indexes
- 2dsphere Indexes
- 2d Indexes
- geoHaystack Indexes
- Hashed Indexes
- 索引特性
- Index Builds on Populated Collections
- 索引交集
- Manage Indexes
- 衡量索引使用
- Indexing Strategies
- Indexing Reference
- 2d索引
- 2dsphere索引
- 复合索引
- geoHaystack索引
- Hashed 索引
- 在填充的集合上建立索引
- 索引参考
- 索引策略
- 管理索引
- 多键索引
- 单字段索引
- 文本索引
- 通配符索引
- 安全
- 安全检查列表
- Enable Access Control
- 身份验证
- Users
- Add Users
- Authentication Mechanisms
- SCRAM
- x.509
- Enterprise Authentication Mechanisms
- Kerberos Authentication
- LDAP Proxy Authentication
- LDAP Authorization
- Internal/Membership Authentication
- Deploy Replica Set With Keyfile Authentication
- Update Replica Set to Keyfile Authentication
- Update Replica Set to Keyfile Authentication (No Downtime)
- Rotate Keys for Replica Sets
- Deploy Sharded Cluster with Keyfile Authentication
- Update Sharded Cluster to Keyfile Authentication
- Update Sharded Cluster to Keyfile Authentication (No Downtime)
- Rotate Keys for Sharded Clusters
- Use x.509 Certificate for Membership Authentication
- Upgrade from Keyfile Authentication to x.509 Authentication
- Rolling Update of x.509 Cluster Certificates that Contain New DN
- Role-Based Access Control
- TLS/SSL (Transport Encryption)
- Encryption at Rest
- Client-Side Field Level Encryption
- 审计
- Network and Configuration Hardening
- Implement Field Level Redaction
- Security Reference
- Create a Vulnerability Report
- Appendix
- 附录
- 启用访问控制
- 网络和配置强化
- 安全参考
- 改变流
- 复制集
- 复制集成员
- 副本集日志
- Replica Set Data Synchronization
- 副本集部署架构
- Replica Set High Availability
- Replica Set Read and Write Semantics
- Replica Set Deployment Tutorials
- Member Configuration Tutorials
- Replica Set Maintenance Tutorials
- Change the Size of the Oplog
- Perform Maintenance on Replica Set Members
- Force a Member to Become Primary
- Resync a Member of a Replica Set
- Configure Replica Set Tag Sets
- Reconfigure a Replica Set with Unavailable Members
- Manage Chained Replication
- Change Hostnames in a Replica Set
- Configure a Secondary’s Sync Target
- Replication Reference
- 副本集数据同步
- 分片
- 分片集群组成]
- 片键
- 哈希分片
- 范围分片
- 部署分片集群
- 区域
- Data Partitioning with Chunks
- Balancer
- Administration
- Config Server Administration
- Replace a Config Server
- View Cluster Configuration
- Restart a Sharded Cluster
- Migrate a Sharded Cluster to Different Hardware
- Add Shards to a Cluster
- Remove Shards from an Existing Sharded Cluster
- Clear jumbo Flag
- Back Up Cluster Metadata
- Convert Sharded Cluster to Replica Set
- Convert a Replica Set to a Sharded Cluster
- Convert a Shard Standalone to a Shard Replica Set
- Sharding Reference
- 分片键
- Zone
- 管理权限
- 产品说明
- Operations Checklist
- Development Checklist
- Performance
- 配置和维护
- Data Center Awareness
- MongoDB Backup Methods
- Back Up and Restore with Filesystem Snapshots
- Back Up and Restore with MongoDB Tools
- Restore a Replica Set from MongoDB Backups
- Backup and Restore Sharded Clusters
- Back Up a Sharded Cluster with File System Snapshots
- Back Up a Sharded Cluster with Database Dumps
- Schedule Backup Window for Sharded Clusters
- Restore a Sharded Cluster
- Recover a Standalone after an Unexpected Shutdown
- Monitoring for MongoDB
- 开发检查表
- MogoDB 备份方法
- 操作检查表
- MongoDB性能
- 存储
- 常见问题
- 参考
- Operators
- Query and Projection Operators
- Comparison Query Operators
- Logical Query Operators
- Element Query Operators
- Evaluation Query Operators
- Geospatial Query Operators
- Array Query Operators
- Bitwise Query Operators
- $comment
- 查询与映射运算符
- 更新运算符
- Field Update Operators
- Array Update Operators
- Bitwise Update Operator
- Aggregation Pipeline Stages
- $addFields (aggregation)
- $bucket (aggregation)
- $bucketAuto (aggregation)
- $collStats (aggregation)
- $count (aggregation)
- $currentOp (aggregation)
- $facet (aggregation)
- $geoNear (aggregation)
- $graphLookup (aggregation)
- $group (aggregation)
- $indexStats (aggregation)
- $limit (aggregation)
- $listLocalSessions
- $listSessions
- $lookup (aggregation)
- $match (aggregation)
- $merge (aggregation)
- $out (aggregation)
- $planCacheStats
- $project (aggregation)
- $redact (aggregation)
- $replaceRoot (aggregation)
- $replaceWith (aggregation)
- $sample (aggregation)
- $set (aggregation)
- $skip (aggregation)
- $sort (aggregation)
- $sortByCount (aggregation)
- $unionWith (aggregation)
- $unset (aggregation)
- $unwind (aggregation)
- Aggregation Pipeline Operators
- $sin (aggregation)
- $abs (aggregation)
- $slice (aggregation)
- $accumulator (aggregation)
- $split (aggregation)
- $acos (aggregation)
- $sqrt (aggregation)
- $acosh (aggregation)
- $add (aggregation)
- $addToSet (aggregation)
- $allElementsTrue (aggregation)
- $and (aggregation)
- $anyElementTrue (aggregation)
- $arrayElemAt (aggregation)
- $arrayToObject (aggregation)
- $asin (aggregation)
- $asinh (aggregation)
- $sum (aggregation)
- $atan (aggregation)
- $atan2 (aggregation)
- $tan (aggregation)
- $atanh (aggregation)
- $avg (aggregation)
- $binarySize (aggregation)
- $bsonSize (aggregation)
- $ceil (aggregation)
- $toInt (aggregation)
- $cmp (aggregation)
- $concat (aggregation)
- $concatArrays (aggregation)
- $cond (aggregation)
- $convert (aggregation)
- $cos (aggregation)
- $dateFromParts (aggregation)
- $dateToParts (aggregation)
- $type (aggregation)
- $dateFromString (aggregation)
- $week (aggregation)
- $dateToString (aggregation)
- $year (aggregation)
- $dayOfMonth (aggregation)
- $zip (aggregation)
- $dayOfWeek (aggregation)
- $dayOfYear (aggregation)
- $degreesToRadians (aggregation)
- $divide (aggregation)
- $eq (aggregation)
- $exp (aggregation)
- $filter (aggregation)
- $first (aggregation accumulator)
- $first (aggregation)
- $floor (aggregation)
- $function (aggregation)
- $gt (aggregation)
- $gte (aggregation)
- $hour (aggregation)
- $ifNull (aggregation)
- $in (aggregation)
- $indexOfArray (aggregation)
- $indexOfBytes (aggregation)
- $indexOfCP (aggregation)
- $isArray (aggregation)
- $isNumber (aggregation)
- $isoDayOfWeek (aggregation)
- $isoWeek (aggregation)
- $isoWeekYear (aggregation)
- $last (aggregation accumulator)
- $last (aggregation)
- $let (aggregation)
- $literal (aggregation)
- $ln (aggregation)
- $log (aggregation)
- $log10 (aggregation)
- $lt (aggregation)
- $lte (aggregation)
- $trim (aggregation)
- $map (aggregation)
- $max (aggregation)
- $mergeObjects (aggregation)
- $meta
- $min (aggregation)
- $millisecond (aggregation)
- $minute (aggregation)
- $mod (aggregation)
- $month (aggregation)
- $multiply (aggregation)
- $ne (aggregation)
- $not (aggregation)
- $objectToArray (aggregation)
- $or (aggregation)
- $pow (aggregation)
- $push (aggregation)
- $radiansToDegrees (aggregation)
- $range (aggregation)
- $reduce (aggregation)
- $regexFind (aggregation)
- $regexFindAll (aggregation)
- $regexMatch (aggregation)
- $replaceOne (aggregation)
- $replaceAll (aggregation)
- $reverseArray (aggregation)
- $round (aggregation)
- $rtrim (aggregation)
- $second (aggregation)
- $setDifference (aggregation)
- $setEquals (aggregation)
- $setIntersection (aggregation)
- $setIsSubset (aggregation)
- $setUnion (aggregation)
- $size (aggregation)
- $slice (aggregation)
- $split (aggregation)
- $sqrt (aggregation)
- $stdDevPop (aggregation)
- $stdDevSamp (aggregation)
- $strcasecmp (aggregation)
- $strLenBytes (aggregation)
- $strLenCP (aggregation)
- $substr (aggregation)
- $substrBytes (aggregation)
- $substrCP (aggregation)
- $subtract (aggregation)
- $sum (aggregation)
- $switch (aggregation)
- $tan (aggregation)
- $toBool (aggregation)
- $toDate (aggregation)
- $toDecimal (aggregation)
- $toDouble(aggregation)
- $toInt (aggregation)
- $toLong (aggregation)
- $toObjectId (aggregation)
- $toString (aggregation)
- $toLower (aggregation)
- $toUpper (aggregation)
- $trim (aggregation)
- $trunc (aggregation)
- $type (aggregation)
- $week (aggregation)
- $year (aggregation)
- $zip (aggregation)
- 查询修饰符
- $comment
- $explain
- $hint
- $max
- $maxTimeMS
- $min
- $orderby
- $query
- $returnKey
- $showDiskLoc
- $natural
- 聚合管道操作符
- $abs (aggregation)
- $acos (aggregation)
- $acosh (aggregation)
- $add (aggregation)
- $addToSet (aggregation)
- $and (aggregation)
- $anyElementTrue (aggregation)
- $arrayElemAt (aggregation)
- $arrayToObject (aggregation)
- $asin (aggregation)
- $asinh (aggregation)
- $atan (aggregation)
- $atan2 (aggregation)
- $atanh (aggregation)
- $avg (aggregation)
- $ceil (aggregation)
- $cmp (aggregation)
- $concat (aggregation)
- $concatArrays (aggregation)
- $cond (aggregation)
- $convert (aggregation)
- $cos (aggregation)
- $dateFromParts (aggregation)
- $dateFromString (aggregation)
- $dateToParts (aggregation)
- $dateToString (aggregation)
- $literal (aggregation)
- 聚合管道阶段
- 数据库命令
- Aggregation Commands
- aggregate
- count
- distinct
- mapReduce
- Geospatial Commands
- geoSearch
- Query and Write Operation Commands
- delete
- find
- findAndModify
- getLastError
- getMore
- insert
- resetError
- update
- 查询计划缓存命令
- planCacheClear
- planCacheClearFilters
- planCacheListFilters
- planCacheSetFilter
- 认证命令
- authenticate
- getnonce
- logout
- User Management Commands
- createUser
- dropAllUsersFromDatabase
- dropUser
- grantRolesToUser
- revokeRolesFromUser
- updateUser
- usersInfo
- Role Management Commands
- createRole
- dropRole
- dropAllRolesFromDatabase
- grantPrivilegesToRole
- grantRolesToRole
- invalidateUserCache
- revokePrivilegesFromRole
- revokeRolesFromRole
- rolesInfo
- updateRole
- Replication Commands
- applyOps
- isMaster
- replSetAbortPrimaryCatchUp
- replSetFreeze
- replSetGetConfig
- replSetGetStatus
- replSetInitiate
- replSetMaintenance
- replSetReconfig
- replSetResizeOplog
- replSetStepDown
- replSetSyncFrom
- Sharding Commands
- addShard
- addShardToZone
- balancerCollectionStatus
- balancerStart
- balancerStatus
- balancerStop
- checkShardingIndex
- clearJumboFlag
- cleanupOrphaned
- enableSharding
- flushRouterConfig
- getShardMap
- getShardVersion
- isdbgrid
- listShards
- medianKey
- moveChunk
- movePrimary
- mergeChunks
- refineCollectionShardKey
- removeShard
- removeShardFromZone
- setShardVersion
- shardCollection
- shardingState
- split
- splitChunk
- splitVector
- unsetSharding
- updateZoneKeyRange
- Sessions Commands
- abortTransaction
- commitTransaction
- endSessions
- killAllSessions
- killAllSessionsByPattern
- killSessions
- refreshSessions
- startSession
- Administration Commands
- cloneCollectionAsCapped
- collMod
- compact
- connPoolSync
- convertToCapped
- create
- createIndexes
- currentOp
- drop
- dropDatabase
- dropConnections
- dropIndexes
- filemd5
- fsync
- fsyncUnlock
- getDefaultRWConcern
- getParameter
- killCursors
- killOp
- listCollections
- listDatabases
- listIndexes
- logRotate
- reIndex
- renameCollection
- setFeatureCompatibilityVersion
- setIndexCommitQuorum
- setParameter
- setDefaultRWConcern
- shutdown
- Diagnostic Commands
- availableQueryOptions
- buildInfo
- collStats
- connPoolStats
- connectionStatus
- cursorInfo
- dataSize
- dbHash
- dbStats
- diagLogging
- driverOIDTest
- explain
- features
- getCmdLineOpts
- getLog
- hostInfo
- isSelf
- listCommands
- lockInfo
- netstat
- ping
- profile
- serverStatus
- shardConnPoolStats
- top
- validate
- whatsmyuri
- 免费监控命令
- getFreeMonitoringStatus
- setFreeMonitoring
- 数据库命令
- logApplicationMessage
- 管理命令
- 聚合命令
- 诊断命令
- 地理空间命令
- 查询和写操作命令
- 复制命令
- 角色管理命令
- 会话命令
- 分片命令
- 用户管理命令
- mongo Shell 方法
- Collection Methods
- db.collection.aggregate()
- db.collection.bulkWrite()
- db.collection.copyTo()
- db.collection.count()
- db.collection.countDocuments()
- db.collection.estimatedDocumentCount()
- db.collection.createIndex()
- db.collection.createIndexes()
- db.collection.dataSize()
- db.collection.deleteOne()
- db.collection.deleteMany()
- db.collection.distinct()
- db.collection.drop()
- db.collection.dropIndex()
- db.collection.dropIndexes()
- db.collection.ensureIndex()
- db.collection.explain()
- db.collection.find()
- db.collection.findAndModify()
- db.collection.findOne()
- db.collection.findOneAndDelete()
- db.collection.findOneAndReplace()
- db.collection.findOneAndUpdate()
- db.collection.getIndexes()
- db.collection.getShardDistribution()
- db.collection.getShardVersion()
- db.collection.hideIndex()
- db.collection.insert()
- db.collection.insertOne()
- db.collection.insertMany()
- db.collection.isCapped()
- db.collection.latencyStats()
- db.collection.mapReduce()
- db.collection.reIndex()
- db.collection.remove()
- db.collection.renameCollection()
- db.collection.replaceOne()
- db.collection.save()
- db.collection.stats()
- db.collection.storageSize()
- db.collection.totalIndexSize()
- db.collection.totalSize()
- db.collection.unhideIndex()
- db.collection.update()
- db.collection.updateOne()
- db.collection.updateMany()
- db.collection.watch()
- db.collection.validate()
- Cursor Methods
- cursor.addOption()
- cursor.allowDiskUse()
- cursor.allowPartialResults()
- cursor.batchSize()
- cursor.close()
- cursor.isClosed()
- cursor.collation()
- cursor.comment()
- cursor.count()
- cursor.explain()
- cursor.forEach()
- cursor.hasNext()
- cursor.hint()
- cursor.isExhausted()
- cursor.itcount()
- cursor.limit()
- cursor.map()
- cursor.max()
- cursor.maxTimeMS()
- cursor.min()
- cursor.next()
- cursor.noCursorTimeout()
- cursor.objsLeftInBatch()
- cursor.pretty()
- cursor.readConcern()
- cursor.readPref()
- cursor.returnKey()
- cursor.showRecordId()
- cursor.size()
- cursor.skip()
- cursor.sort()
- cursor.tailable()
- cursor.toArray()
- Database Methods
- db.adminCommand()
- db.aggregate()
- db.cloneDatabase()
- db.commandHelp()
- db.copyDatabase()
- db.createCollection()
- db.createView()
- db.currentOp()
- db.dropDatabase()
- db.eval()
- db.fsyncLock()
- db.fsyncUnlock()
- db.getCollection()
- db.getCollectionInfos()
- db.getCollectionNames()
- db.getLastError()
- db.getLastErrorObj()
- db.getLogComponents()
- db.getMongo()
- db.getName()
- db.getProfilingLevel()
- db.getProfilingStatus()
- db.getReplicationInfo()
- db.getSiblingDB()
- db.help()
- db.hostInfo()
- db.isMaster()
- db.killOp()
- db.listCommands()
- db.logout()
- db.printCollectionStats()
- db.printReplicationInfo()
- db.printShardingStatus()
- db.printSlaveReplicationInfo()
- db.resetError()
- db.runCommand()
- db.serverBuildInfo()
- db.serverCmdLineOpts()
- db.serverStatus()
- db.setLogLevel()
- db.setProfilingLevel()
- db.shutdownServer()
- db.stats()
- db.version()
- db.watch()
- Query Plan Cache Methods
- db.collection.getPlanCache()
- PlanCache.clear()
- PlanCache.clearPlansByQuery()
- PlanCache.help()
- PlanCache.list()
- Bulk Operation Methods
- db.collection.initializeOrderedBulkOp()
- db.collection.initializeUnorderedBulkOp()
- Bulk()
- Bulk.execute()
- Bulk.find()
- Bulk.find.arrayFilters()
- Bulk.find.collation()
- Bulk.find.hint()
- Bulk.find.remove()
- Bulk.find.removeOne()
- Bulk.find.replaceOne()
- Bulk.find.updateOne()
- Bulk.find.update()
- Bulk.find.upsert()
- Bulk.getOperations()
- Bulk.insert()
- Bulk.tojson()
- Bulk.toString()
- User Management Methods
- db.auth()
- db.changeUserPassword()
- db.createUser()
- db.dropUser()
- db.dropAllUsers()
- db.getUser()
- db.getUsers()
- db.grantRolesToUser()
- db.removeUser()
- db.revokeRolesFromUser()
- db.updateUser()
- passwordPrompt()
- Role Management Methods
- db.createRole()
- db.dropRole()
- db.dropAllRoles()
- db.getRole()
- db.getRoles()
- db.grantPrivilegesToRole()
- db.revokePrivilegesFromRole()
- db.grantRolesToRole()
- db.revokeRolesFromRole()
- db.updateRole()
- Replication Methods
- rs.add()
- rs.addArb()
- rs.conf()
- rs.freeze()
- rs.help()
- rs.initiate()
- rs.printReplicationInfo()
- rs.printSlaveReplicationInfo()
- rs.reconfig()
- rs.remove()
- rs.status()
- rs.stepDown()
- rs.syncFrom()
- Sharding Methods
- sh.addShard()
- sh.addShardTag()
- sh.addShardToZone()
- sh.addTagRange()
- sh.balancerCollectionStatus()
- sh.disableBalancing()
- sh.enableBalancing()
- sh.disableAutoSplit
- sh.enableAutoSplit
- sh.enableSharding()
- sh.getBalancerHost()
- sh.getBalancerState()
- sh.removeTagRange()
- sh.removeRangeFromZone()
- sh.help()
- sh.isBalancerRunning()
- sh.moveChunk()
- sh.removeShardTag()
- sh.removeShardFromZone()
- sh.setBalancerState()
- sh.shardCollection()
- sh.splitAt()
- sh.splitFind()
- sh.startBalancer()
- sh.status()
- sh.stopBalancer()
- sh.waitForBalancer()
- sh.waitForBalancerOff()
- sh.waitForPingChange()
- sh.updateZoneKeyRange()
- convertShardKeyToHashed
- Free Monitoring Methods
- db.disableFreeMonitoring()
- db.enableFreeMonitoring()
- db.getFreeMonitoringStatus
- Object Constructors and Methods
- BulkWriteResult()
- Date()
- ObjectId
- ObjectId.getTimestamp()
- ObjectId.toString()
- ObjectId.valueOf()
- UUID()
- WriteResult()
- WriteResult.hasWriteError()
- WriteResult.hasWriteConcernError()
- Connection Methods
- connect()
- Mongo()
- Mongo.getDB()
- Mongo.getReadPrefMode()
- Mongo.getReadPrefTagSet()
- Mongo.isCausalConsistency()
- Mongo.setCausalConsistency()
- Mongo.setReadPref()
- Mongo.startSession()
- Mongo.watch()
- Session
- SessionOptions
- Native Methods
- cat()
- cd()
- copyDbpath()
- getHostName()
- getMemInfo()
- hostname()
- isInteractive()
- listFiles()
- load()
- ls()
- md5sumFile()
- mkdir()
- pwd()
- quit()
- removeFile()
- resetDbpath()
- sleep()
- setVerboseShell()
- version()
- _isWindows()
- _rand()
- Client-Side Field Level Encryption Methods
- getKeyVault()
- KeyVault.createKey()
- KeyVault.deleteKey()
- KeyVault.getKey()
- KeyVault.getKeys()
- KeyVault.addKeyAlternateName()
- KeyVault.removeKeyAlternateName()
- KeyVault.getKeyByAltName()
- getClientEncryption()
- ClientEncryption.encrypt()
- ClientEncryption.decrypt()
- mongo Shell 方法
- MongoDB Package Components
- Configuration File Options
- MongoDB Server Parameters
- MongoDB Limits and Thresholds
- Explain Results
- System Collections
- 连接字符串URI格式
- 排序
- MongoDB的Wire协议
- 日志消息
- Exit Codes and Statuses
- 词汇表
- 默认的MongoDB端口
- Default MongoDB Read Concerns/Write Concerns
- 服务器会话
- Configuration File Options
- 默认的MongoDB读/写关注
- 退出代码和状态
- MongoDB Limits and Thresholds
- Operators
- 更新说明
- Release Notes for MongoDB 4.4
- Release Notes for MongoDB 4.2
- Release Notes for MongoDB 4.0
- Release Notes for MongoDB 3.6
- Release Notes for MongoDB 3.4
- Release Notes for MongoDB 3.2
- Release Notes for MongoDB 3.0
- Release Notes for MongoDB 2.6
- Release Notes for MongoDB 2.4
- Release Notes for MongoDB 2.2
- Release Notes for MongoDB 2.0
- Release Notes for MongoDB 1.8
- Release Notes for MongoDB 1.6
- Release Notes for MongoDB 1.4
- Release Notes for MongoDB 1.2.x
- MongoDB Versioning
- 技术支持
- 开始使用MongoDB开发
- 联系我们
- 更多资料
- 本书使用 GitBook 发布
读取隔离、一致性和近效性
读取隔离、一致性和近效性
在本页面
隔离保证
读取未提交
根据读取的关注点,客户端可以在持久写入之前看到写入的结果:
- 不考虑一个写操作的写关注,其他客户端使用
local
或者available
的读关注级别都可以看到写操作的结果。 - 使用
local
或available
读取关注级别的客户端可以读取数据,这些数据随后可能会在副本集故障转移期间回滚。
对于多文档事务中的操作,当事务提交时,在事务中进行的所有数据更改都将保存并在事务外部可见。也就是说,一个事务在回滚其他事务时将不会提交其某些更改。
在提交事务之前,在事务外部看不到在事务中进行的数据更改。
但是,当事务写入多个分片时,并非所有外部读取操作都需要等待已提交事务的结果在所有分片上可见。例如,如果提交了一个事务,并且在分片A上可以看到写1,但是在分片B上还看不到写2,则外部一个读关注级别为local
的读操作可以读取写1的结果而看不到写2。
读未提交是默认的隔离级别,适用于mongod独立实例以及复制集和分片群集。
读取未提交和单个文档原子性
对于单个文档,写操作是原子性的。 即,如果写操作正在更新文档中的多个字段,则读操作将永远不会看到仅更新了某些字段的文档。 但是,尽管客户端可能看不到部分更新的文档,但读未提交意味着并发读取操作仍可以在使更改持久之前看到更新的文档。
对于以独立模式部署的 mongod
实例,对单个文档的一组读写操作是线性的。 使用复制集时,只有在没有回滚的情况下,对单个文档的一组读取和写入操作才是线性的。
读取未提交和多文档写入
当单个写入操作(例如 db.collection.updateMany()
)修改多个文档时,每个文档的修改都是原子的,但整个操作不是原子的。
当单个写入操作(例如db.collection.updateMany()
)修改多个文档时,每个文档的修改都是原子的,但整个操作不是原子的。
当执行多文档写操作时,无论是通过单个写操作还是通过多个写操作,其他操作都可能会交错。
对于需要原子性地读写多个文档(在单个或多个集合中)的情况,MongoDB支持多文档事务:
- 4.0版本中,MongoDB支持副本集内的多文档事务。
- 4.2版本中,MongoDB引入了分布式事务,从而增加了对分片群集上多文档事务的支持,并结合了对副本集上多文档事务的现有支持。
关于MongoDB事务的细节,请参考事务页。
[warning] 重要
在大多数情况下,与单文档写入相比,多文档事务产生的性能成本更高,并且多文档事务的可用性并不能替代有效的架构设计。 在许多情况下,非结构化化数据模型(嵌入式文档和数组)将继续是您的数据和用例的最佳选择。 也就是说,在许多情况下,适当地对数据建模将最大程度地减少对多文档交易的需求。
关于其他事务使用方面的注意事项(比如运行时显示和oplog大小限制等),请参考生产注意事项.
在不隔离多文档写入操作的情况下,MongoDB表现出以下行为:
- 非时间点(
Non-point-in-time
)读取操作。假设读取操作在时间t1开始并开始读取文档。然后,写操作在稍后的某个时间t2提交对其中一个文档的更新。读操作可能会看到文档的更新后版本,因此看不到数据的point-in-time快照。 - 非可序列化的操作。假设读取操作在时间t1读取文档d1,而写入操作在稍后的时间t3更新d1。这引入了读写依赖性,因此,如果要序列化操作,则读取操作必须先于写入操作。但是还假设写操作在时间t2更新文档d2,而读取操作随后在稍后的时间t4读取d2。这就引入了写-读依赖关系,它将要求读操作在可序列化时间表中在写操作之后进行。有一个依赖循环,使可序列化成为不可能。
- 读取操作可能会丢失在读取操作过程中更新的匹配文档。
游标快照
在某些情况下,MongoDB游标可以多次返回同一个文档。 当游标返回文档时,其他操作可能会与查询交错。 如果其中某些操作更改了查询使用的索引上的索引字段; 那么光标将多次返回同一文档。
如果您的集合中有一个或多个从未修改过的字段,则可以在此字段或这些字段上使用唯一索引,这样查询将最多返回每个文档一次。 使用hint()
查询可显式强制查询使用该唯一索引。
单调写
默认的,对于standalone和复制集,MongoDB提供单调写入保证。
对于分片集群的单调写入,参考因果一致性。
实时顺序
3.4后新引入
对于主节点上的读取和写入操作,如果将读关注设置为linearizable
,将写关注设置为majority
,那么这种读写模型组合可以使多个线程可以在单个文档上执行读写操作,就好像单个线程实时执行了这些操作一样 ; 也就是说,这些读写的相应计划被认为是线性的。
亦可参考:
因果一致性
3.6后新引入
如果操作在逻辑上取决于先前的操作,则这些操作之间存在因果关系。 例如,基于指定条件删除所有文档的写入操作和验证删除操作的后续读取操作具有因果关系。
在因果一致的会话中,MongoDB按照尊重因果关系的顺序执行因果操作,并且客户观察到与因果关系一致的结果。
客户端会话与因果一致性保证
为了提供因果一致性,MongoDB 3.6在客户端会话中启用因果一致性。 因果一致的会话表示具有majority
的读关注级别的读操作和具有majority
的写关注级别的写操作的关联序列具有因果关系,这由它们的顺序反映出来。 应用程序必须确保一次只有一个线程在客户端会话中执行这些操作。
对于因果相关的操作:
- 客户端开始一个客户端会话
[warning] 重要
客户端会话仅在以下情况下保证因果一致性:
读取操作的读关注级别为
majority
;即返回数据已被大多数副本集成员确认并且是持久化的。写操作的写关注级别为
majority
;即要求确认该操作已应用于副本集中大多数可投票成员。关于因果一致性和多种读关注级别/写关注级别,请参考因果一致性和读/写关注级别。
当客户端发出具有
majority
读关注和majority
写关注的读取序列时,客户端将会话信息包含在每个操作中。对于与会话相关联的每个具有
majority
读关注的读取操作和具有majority
写关注的写入操作,即使操作出错,MongoDB也会返回操作时间和集群时间。 客户端会话跟踪操作时间和群集时间。
[success] 注意
对于未确认的
(w:0)
写操作,MongoDB不返回操作时间和群集时间。未经确认的写入并不表示任何因果关系。尽管MongoDB在客户端会话中返回读操作和已确认写操作的操作时间和集群时间,但是只有具有
majority
读关注的读取操作和具有majority
写关注的写入操作才能保证因果一致性。 有关详细信息,请参见因果一致性和读/写关注级别。
- 相关的客户端会话会跟踪这两个时间字段。
[success] 注意
不同会话之间的操作可以因果一致。 MongoDB驱动程序和mongo Shell提供了推进客户端会话的操作时间和集群时间的方法。 因此,客户端可以推进一个客户端会话的群集时间和操作时间,使其与另一客户端会话的操作保持一致。
因果一致性保证
下表列出了因果一致会话为具有majority
读关注的读取操作和具有majority
写关注点的写入操作提供的因果一致性保证。
保证 | 描述 |
---|---|
写后读 | 读操作可以正确读到之前写的结果。 |
单调读 | 多个读操作会返回一样的 比如在一个会话中“ - 写操作1在写操作2前, - 读操作1在读操作2前,并且, - 读操作1返回了写操作2的结果 那么读操作2并不会返回写操作1的结果。 |
单调写 | 写操作按顺序进行。 比如,如果会话中写操作1在写操作2前,数据在写操作2的状态必须是写操作1完成后的状态。其他写入操作可以在写操作1和写操作2之间进行交错,但写操作2不可能在写操作1之前进行。 |
读后写 | 写操作在读操作后执行。 即,写入时的数据状态必须包含之前的读取操作的数据状态。 |
读偏好
这些保证适用于MongoDB部署的所有成员。 例如,如果在因果关系一致的会话中发出具有majority
写关注级别的写操作,然后发出一个具有majority
读关注级别的从节点(即,读偏好为secondary
)读操作,则读取操作将反映写入操作后的数据库状态。
隔离性
因果一致的会话内的操作与会话外的操作不是隔离的。 如果并发写操作在会话的写操作和读取操作之间交错,则会话的读操作可能返回反映会话写操作之后发生的写操作的结果。
MongoDB驱动
提示:
应用程序必须确保一次只有一个线程在客户端会话中执行这些操作。
客户端需要使用MongoDB 3.6或更高版本的MongoDB驱动程序:
Java 3.6+ | C 2.5+ | Perl 2.0+ |
---|---|---|
Python 3.6+ | Node 3.0+ | PHPC 1.4+ |
C 1.9+ | Ruby 2.5+ | Scala 2.2+ |
示例
重要**
因果一致性会话只能保证对于读关注级别为
majority
以及写关注级别为majority
的读取操作的因果一致性。
考虑一个维护各种项目的当前和历史数据的items
集合。 只有历史数据的end
日期为非空。 如果项目的sku
值更改,则具有旧sku
值的文档需要使用end
日期进行更新,此后,将使用当前sku
值插入新文档。 客户端可以使用因果一致的会话来确保更新在插入之前发生。
(以python为例,其他实例查看原链接)
with client.start_session(causal_consistency=True) as s1:
current_date = datetime.datetime.today()
items = client.get_database(
'test', read_concern=ReadConcern('majority'),
write_concern=WriteConcern('majority', wtimeout=1000)).items
items.update_one(
{'sku': "111", 'end': None},
{'$set': {'end': current_date}}, session=s1)
items.insert_one(
{'sku': "nuts-111", 'name': "Pecans",
'start': current_date}, session=s1)
如果另一个客户端需要读取所有当前的sku值,则可以将集群时间和操作时间推进到另一个会话的集群时间和操作时间,以确保该客户端与另一个会话有因果关系,并在两次写入之后读取:
with client.start_session(causal_consistency=True) as s2:
s2.advance_cluster_time(s1.cluster_time)
s2.advance_operation_time(s1.operation_time)
items = client.get_database(
'test', read_preference=ReadPreference.SECONDARY,
read_concern=ReadConcern('majority'),
write_concern=WriteConcern('majority', wtimeout=1000)).items
for item in items.find({'end': None}, session=s2):
print(item)
限制
以下生成内存数据结构的操作并不是因果一致性的:
操作 | 备注 |
---|---|
collStats | |
$collStats with latencyStats option. | |
$currentOp | 如果操作和一个因果一致性的客户端会话相关,则会返回错误。 |
createIndexes | |
dbHash | MongoDB4.2以后的版本才支持 |
dbStats | |
getMore | 如果操作和一个因果一致性的客户端会话相关,则会返回错误。 |
$indexStats | |
mapReduce | MongoDB4.2以后的版本才支持 |
ping | 如果操作和一个因果一致性的客户端会话相关,则会返回错误。 |
serverStatus | 如果操作和一个因果一致性的客户端会话相关,则会返回错误。 |
validate | MongoDB4.2以后的版本才支持 |
原文链接:https://docs.mongodb.com/manual/core/read-isolation-consistency-recency/
译者:刘翔 杨帅
校对:徐雷
参见
原文 - Read Isolation, Consistency, and Recency
Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2020-12-18 11:34:57