- 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 发布
在填充的集合上建立索引
在填充的集合上建立索引
在本页面
MongoDB 4.2版本新变化
针对已填充的集合的MongoDB索引构建需要对该集合的排他性读写锁定。需要对集合进行读取或写入锁定的操作必须等待,直到mongod
释放锁定为止 。MongoDB 4.2使用了优化的构建过程,该过程仅在索引构建的开始和结束时持有排他锁。其余的构建过程将产生交错的读写操作。
索引构建过程总结如下:
- 初始化
mongod 进程对正在编制索引的集合使用独占锁。所有对该集合的读写操作将阻塞直到mongod
进程释放锁。在此期间,应用程序无法访问集合。
数据摄取和加工
mongod
进程释放上一过程中获取的所有锁,然后针对被索引的集合获取一系列意向锁。在此期间,应用程序可以对集合发出读写操作。清理
mongod
进程释放上一过程中获取的所有锁,然后针对被索引集合获取独占锁。这时将阻塞对该集合所有读写操作直到mongod
进程释放锁。应用程序此时无法访问该集合。完成
mongod
进程标记索引状态为已可用,然后释放索引构建过程中的所有锁。
索引构建过程中的加锁描述细节参见Index Build Process章节。更深入了解MongoDB的加锁行为参见FAQ: Concurrency。 行为 MongoDB 4.2索引构建完全替代了以前MongoDB版本中支持的索引构建过程。如果指定为createIndexes
或它的shell助手createIndexes()
和createIndexes()
, MongoDB会忽略后台索引构建选项。
与前景和背景构建进行比较
MongoDB的早期版本支持在前台或后台构建索引。前台索引构建速度很快,能够生成更高效的索引数据结构,但是需要在构建期间阻塞对被索引的集合的父数据库的所有读写访问。后台索引构建速度较慢,效率较低,但允许在构建过程中对数据库及其集合进行读写访问。
MongoDB 4.2版本变化
MongoDB 4.2索引构建只在构建过程的开始和结束时对被索引的集合获得独占锁,以保护元数据的更改。构建过程的其余部分使用后台索引构建的生成行为来最大化构建期间对集合的读写访问。4.2索引构建仍然产生高效的索引数据结构,尽管有更宽松的锁定行为。
MongoDB 4.2的索引构建性能至少与后台索引构建相当。对于在构建过程中很少或没有收到更新的工作负载,4.2索引构建构建的速度可以与基于相同数据的前台索引构建的速度一样快。
使用db.currentOp()
命令监视正在进行的索引构建的进度。
索引构建期间的冲突约束 对集合具有强制约束作用的索引,例如:unique 索引, mongod
进程会在索引构建完成后对所有预先存在的和并发写入的文档进行约束性检查。如果任何文档违反了索引约束条件,mongod
进程将终止构建并抛出错误。
举例:对inventory
集合的product_sku
属性构建unique特性索引。如果任意文档的product_sku
属性有重复值,索引构建过程仍可成功开始,如果在构建结束时仍然存在任何冲突,mongod
进程会终止构建并抛出错误。
类似的,在索引构建的过程中,应用程序可成功对inventory
集合写入product_sku
属性值重复的文档。如果在构建结束时存在任何索引约束冲突,mongod
进程会终止构建并抛出错误。
降低因违反约束而导致索引生成失败的风险:
- 校验集合中没有违反索引约束的文档。
- 停止所有可能违反该集合索引约束条件的应用程序写入操作。
索引构建对数据库性能的影响 高负载写入时的索引构建
在目标集合处于高负载写入状态时执行索引构建操作,会造成写入性能下降和更长的索引构建时间。
考虑指定一个维护窗口用于构建索引,在此期间停止或减少对目标集合的写入操作。以减少索引生成过程对性能的潜在负面影响。
可用系统内存不足时的索引构建
命令支持在集合上构建多个索引。createIndexes
命令同时使用内存和磁盘上的临时文件空间完成索引构建。createIndexes
命令默认的内存使用限制是500MB,该空间在所有使用createIndexes
命令生成的索引之间共享。一旦在构建索引时到达该空间限制,createIndexes
命令将使用--dbpath
目录下_tmp
文件夹下的临时磁盘文件空间,用于完成索引构建。
你可以自定义maxIndexBuildMemoryUsageMegabytes
参数,更改该空间大小限制。设置更高的内存空间可以在索引大小超500MB时更快完成索引构建。当然,该参数设置过高也会导致占用太多无用内存造成系统内存错误。
如果主机内存有限,你可能需要安排一个维护期,增加整个系统内存,再更改mongod
进程中的内存参数设置。
复制集中的索引构建 尽量减少建立索引对以下方面的影响:
- 复制集中,使用滚动索引生成策略,如Build Indexes on Replica Sets章节所述。
- 拥有分片复制集的分片集群中,使用滚动索引生成策略,如Build Indexes on Sharded Clusters章节所述。
你可以在primary节点执行索引构建。索引生成完成后,secondaries节点进行复制并开始索引构建。复制集中在开始构建索引之前请注意如下风险:
Secondaries节点可能不进行同步
Secondary节点的索引构建将阻塞应用正在执行的对构建索引集合的事务操作。 mongod
进程在构建索引完成前将无法使用任何oplog。
如果索引生成在执行操作或命令时持有独占锁,则对被索引集合的复制写操作也可能被延迟到索引构建完成之后。mongod
进程无法使用任何oplog直到锁释放。如果复制延迟时间超过secondary节点的oplog window,secondary将不进行同步,需要通过resynchronization来恢复。
在构建索引之前,使用rs.printReplicationInfo()
命令鉴别每个副本集成员配置的时间区间中可处理的oplog大小。你可以增大oplog大小increase the oplog size,降低不同步的概率。例如,设置oplog的窗口可以覆盖72个小时的操作记录,只要确保secondary节点可以容忍这么久的复制延迟。
或者在维护时间窗口中执行索引构建,应用程序停止对该索引集合的所有事物操作、写操作和元数据操作。
Secondary节点的索引构建可能造成读写操作延迟
MongoDB 4.2索引生成过程的开始和结束时获取正在索引的集合的独占锁。当secondary节点索引生成持有独占锁时,该secondary节点将暂停任何读写操作,直到索引生成释放该锁为止。
索引生成完成后,辅助进程索引将删除
在secondary节点完成索引构建的复制之前,在primary节点删除索引,将不会中断secondary节点的构建。当secondary节点执行索引删除的复制操作时,其须等待之前的索引生成操作执行复制完毕。此外,由于索引删除是集合上的元数据操作,因此索引删除会暂停该secondary节点上的复制。
构建失败和恢复 单个mongod
进程的索引构建中断 如果mongod
进程在索引构建时终止了,索引构建任务和所有进程将丢失。重启mongod
进程不会重新执行索引构建,你必须重新运行createIndex()
操作来重启索引构建。
Primary节点mongod
进程的索引构建中断 如果primary节点在索引构建时停止了,索引构建任务和所有进程将丢失。你必须重新运行createIndex()
操作来重启索引构建。 Secondary节点mongod
进程的索引构建中断 如果secondary节点在索引构建时停止了,索引构建任务将保留。重启 mongod
进程将恢复索引构建并从头重新开始。
启动进程会在任意已恢复的索引生成之后暂停。所有操作,包括复制将进入等待直到索引构建完成。如果secondary节点的oplog未在时间窗口区间完成缩影索引构建的复制,secondary不再进行这部分oplog的复制集的同步,需要resynchronization恢复。
如果你重启了mongod
进程作为独立的复制集节点实例或删除--replSetName
)。mongod
进程仍将从头恢复索引构建。你可以使用storage.indexBuildRetry
配置文件设置或写入命令行参数--noIndexBuildRetry
。
MONGODB 4.0以上版本
你不能对副本集中的一个
mongod
进程实例,设置storage.indexBuildRetry
选项 或--noIndexBuildRetry
选项。
构建过程中的回滚 从4.0版本开始,MongoDB在任意正在执行索引构建的进程完成后进行rollback。 监视进行中的索引构建 你可以在mongo
shell中执行db.currentOp()
命令,查看索引构建操作的状态。筛选当前操作中的索引创建操作,参见Active Indexing Operations操作。
msg
包含了索引构建当前阶段的完成百分比。
终止进行中的索引构建 终止primary节点或单个 mongod
进程中正在执行的索引构建命令,请在mongo
进程中使用db.killOp()
命令。当终止索引生成时,db.killOp()
命令可能不会立即执行,并可能在大部分索引生成操作完成后执行。
你无法终止一个已经在复制集secondary节点进行复制的索引构建操作。你必须首先在primary节点drop
删除索引。secondary节点将复制删除操作并在索引构建完成后删除索引。所用复制操作将阻塞直到索引构建完成并执行完删除操作。
尽量降低复制集和拥有复制集的分片集群的构建索引影响,参见:
- 在复制集上建立索引
- 在分片群集上建立索引 索引建立过程 如下表格描述索引构建过程中的每个阶段:
阶段 | 描述 |
---|---|
Lock | mongod 进程获得索引集合的独占X 锁。该集合的所有读写操作被阻塞,包括应用程序对该集合所有复制写操作或者元数据指令。mongod 进程不会释放独占锁。 |
初始化 | mongod 进程在该初始状态创建三个数据结构:初始索引元数据项。一张临时表("side writes table"),用来存储构建过程中对索引集合进行写入时生成的key。一张临时表(“constraint violation table”),用于存储可能导致重复键约束冲突的所有文档。 |
Lock | mongod 进程将之前获取的独占锁X 降级为意图独占锁IX ,[mongod ]进程周期性的释放该锁,允许进行交错读写操作。 |
扫描集合 | mongod 进程对集合中每个文档生成一个key,并将该key存储到外部分类器中,如果 mongod 进程在集合扫描期间发现重复key,它会将该key存储在constraint violation表中以备后续处理。如果mongod进程在生成key时遇到任何其他错误,构建将失败并出现错误。一旦mongod进程完成集合扫描,它将分类的key转储到索引中。 |
进程端写入表 | mongod 使用先进先出方式处理Side Writes Table表中数据,如果遇到重复key,将该key写入constraint violation table表以备后续处理。如果mongod 进程在处理键时出现任何异常错误,构建将失败。对于每个在索引构建过程中写入集合的文档,mongod进程都会给该文档生成一个key,并将其存储到side write table表中。mongod 使用快照系统设置要处理的key的数量限制。 |
Lock | mongod 进程将索引集合上的意图独占锁IX 升级为共享S 锁。这会阻塞该集合的所有写操作,包括应用程序对该集合的任何复制写操作或元数据操作。 |
处理完临时端写表 | mongod 进程继续处理Side Writes Table表中的存量数据。mongod 进程在该阶段可能会暂停复制。如果遇到重复key,将该key写入constraint violation table表以备后续处理。如果mongod 进程在处理键时出现任何异常错误,构建将失败。 |
Lock | mongod 进程将索引集合的共享S 锁升级成独占X 锁。该集合的所有读写操作被阻塞,包括应用程序对该集合所有复制写操作或者元数据指令操作。mongod 进程不会释放独占锁。 |
下侧写表 | mongod 在处理完Side Write Table表中所有数据后将其删除。如果遇到重复key,将该key写入constraint violation table表以备后续处理。如果mongod 进程在处理键时出现任何异常错误,构建将失败。 |
流程约束违规表 | mongod 进程使用先入先出的方式处理Constraint Violation Table表中数据,之后删除该表。如果其中任何键仍然出现重复键错误,mongod 将终止构建并抛出错误。mongod 进程在处理完Constraint Violation Table表后或出现重复键约束时将删除该表。 |
将索引标记为就绪 | mongod 将索引元数据更新为可使用状态。 |
Lock | mongod 进程释放该索引集合的独占X 锁。 |
译者:程哲欣
Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2020-12-18 11:34:57