- 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使用分片键值范围对集合中的数据进行分区。每个范围都定义了一个分片键值的非重叠范围,并且与一个chunk(数据块,下同)相关联。
MongoDB尝试在集群中的各个分片之间平均分配数据块。 分片键与数据块分配的有效性直接相关。 请参阅选择分片键。
重要
- 一旦你对一个集合分片,那么其分片键就不可再改变;也就是说,你不可以对这个集合再重新选择另一个不一样的分片键。
- 从MongoDB4.2版本开始,除非分片键是不可变的
_id
字段,否则你可以更新文档的分片键值。有关更新分片键的详细信息,请参考【修改文档的分片键值】。
在MongoDB4.2之前的版本,文档的分片键字段值是不可变的。
分片键格式
为了将一个集合分片,你必须在sh.shardCollection()
方法中指定目标集合和分片键:
sh.shardCollection( namespace, key )
namespace
参数由字符串
组成,该字符串指定目标集合的完整命名空间。. key
参数由包含一个字段和该字段的索引遍历方向的文档组成。
有关使用散列或范围分片策略对集合进行分片的说明,请参阅【对集合进行分片】。
改变一个文档的分片键值
更新分片键时
必须
在事务
中或以可重试写入
方式在mongos上运行。 不要直接在分片上执行操作。- 您必须在查询过滤器的完整分片键上包含相等条件。 例如,如果一个分片集合内使用
{country:1,userid:1}
作为分片键,要想更新文档的分片键,则必须在查询过滤器中包含country:
。 也可以根据需要在查询中包括其他字段。,userid:
从MongoDB 4.2版本开始,除非分片键字段是不可变的_id
字段,否则您可以更新文档的分片键值。 若要更新,请使用以下操作来更新文档的分片键值:
命令 | 方法 |
---|---|
update with multi: false | db.collection.replaceOne()
db.collection.updateOne()
db.collection.update() with multi: false |
findAndModify | db.collection.findOneAndReplace() db.collection.findOneAndUpdate() db.collection.findAndModify() |
db.collection.bulkWrite()
Bulk.find.updateOne()
如果分片键修改导致将文档移动到另一个分片,则在批量操作中不能指定多个分片键修改;即批量大小为1 。
如果分片键修改不会导致将文档移动到另一个分片,则可以在批量操作中指定多个分片键修改。 |
分片键索引
所有分片集合都必须
具有支持分片键的索引。 即索引可以是分片键的索引;也可以是复合索引,其中分片键是索引的前缀。
- 如果集合为空,则
sh.shardCollection()
在分片键上创建索引(如果该索引尚不存在)。 - 如果集合不为空,则必须先创建索引,然后再使用
sh.shardCollection()
。
如果你删除了分片键的最后一个有效索引,请通过仅在分片键上重新创建索引来恢复。
唯一索引
您不能在哈希索引上指定唯一约束。
对于一个范围分片的集合,只有以下索引可以是唯一的
分片键索引
一个已分片键为前缀的复合索引
默认的
_id
索引; 但是,如果_id
字段不是分片键或分片键的前缀,则_id
索引仅对每个分片强制执行唯一性约束。
关于
_id
索引和唯一性如果
_id
字段不是分片键或分片键的前缀,则_id
索引仅对每个分片(而非跨分片)强制实施唯一性约束。例如,考虑一个跨越两个分片A和B的分片集合(具有分片键
{x:1}
)。由于_id
键不是分片键的一部分,因此该集合可能在分片A中具有_id
值为1
的文档。 以及分片B中_id
值为1
的另一个文档。如果
_id
字段不是分片键也不是分片键的前缀,则MongoDB期望应用程序来保证整个分片上_id
值的唯一性。
唯一的索引约束意味着:
- 对于一个即将要分片的集合,如果该集合具有其他唯一索引,则无法分片该集合。
- 对于已分片的集合,不能在其他字段上创建唯一索引。
通过使用分片键上的唯一索引,MongoDB可以对分片键值实施唯一性约束。 MongoDB在整个键组合上(而不是分片键的单个组件)实施唯一性约束。 要对分片键值实施唯一性约束,请将unique
参数设置为true
传递给sh.shardCollection()
方法:
- 如果集合为空,则
sh.shardCollection()
在分片键上创建唯一索引(如果该索引尚不存在)。 - 如果集合不为空,则必须先创建索引,然后再使用
sh.shardCollection()
。
尽管可以有一个唯一的复合索引,其中分片键是一个前缀,但是如果使用unique参数,则集合必须在分片键上具有唯一索引。
选择一个分片键
分片键的选择会影响可用分片中数据块的创建和分布。 这会影响分片群集内操作的整体效率和性能。
分片键会影响分片群集使用的分片策略的性能和效率。
理想的分片键允许MongoDB在整个集群中均匀地分布所有文档。
至少要综合考虑潜在分片键的基数
,频率
和变化率
等指标。
限制
有关分片键的限制,请参阅分片键限制。
集合大小
在对一个不为空的集合进行分片时,分片键只能为初始分片操作限制最大支持的集合大小。 请参阅分片现有集合数据大小。
重要
一个分片集合在成功分片之后就可以增长到任意大小,没有上限。
分片键基数
分片键的基数确定平衡器可以创建的最大数据块的数目。这会降低或消除集群中水平缩放的有效性。
在任何给定时间,唯一的分片键值最多只能存在一个块上。 如果分片密钥的基数为4,则分片集群中最多只能有4个块,每个块存储一个唯一的分片密钥值。 这也将群集中的有效分片数量也限制为4个-添加额外的分片不会提供任何好处。
下图说明了使用字段X作为分片键的分片群集。 如果X具有低基数,则插入的分布可能类似于以下内容:
在此示例中,集群不会水平扩展,因为传入的写入将仅路由到分片的子集。
具有高基数的分片键虽然可以更好地促进水平扩展,但不能保证在分片集群中均匀分布数据。 分片键的频率
和变化率
也有助于数据分配。 选择分片键时,请考虑每个因素。
如果您的数据模型需要在具有低基数的键上分片,请考虑使用具有较高相对基数的字段的复合索引
。
分片键频率
考虑一个代表分片键值范围的集合-分片键的频率代表给定值在数据中出现的频率。 如果大多数文档仅包含这些值的子集,那么存储这些文档的数据块将成为群集中的瓶颈。 此外,随着这些数据块的增长,它们可能会变成不可分割的数据块
,因为它们无法进一步拆分。 这将降低或消除群集内水平扩展的有效性。
下图说明了使用字段X
作为分片键的分片群集。 如果X
值的子集高频出现,则插入的分布可能类似于以下内容:
低频的分片键不能保证整个分片群集中的数据均匀分布。 分片密钥的基数
和变化率
也有助于数据分配。 选择分片键时,请考虑每个因素。
如果您的数据模型需要在具有高频值的键上分片,请考虑使用具有唯一或低频值的复合索引
。
单调变化的分片键
值单调增加或减少的分片键更有可能将插入内容分布到集群中的单个分片上。
发生这种情况是因为每个集群都有一个大数据块,该大数据块捕获具有maxKey
上限的范围。 maxKey
始终比所有其他值更高。 类似地,有一个块用minKey
的下限捕获范围。 minKey
总是比所有其他值都低。
如果分片键值始终在增加,则所有新插入都将路由到以maxKey
为上限的块。 如果分片键值始终在减小,则所有新插入都将路由到以minKey
为下限的块。 包含该块的分片将成为写操作的瓶颈。
下图说明了使用字段X
作为分片键的分片群集。 如果X
的值单调增加,则插入的分布可能类似于以下内容:
如果分片键值单调递减,则所有插入都将路由到数据块A
。
不能单调更改的分片键不能保证整个分片群集中的数据均匀分布。 分片键的基数
和频率
也有助于数据分配。 选择分片键时,请考虑每一个因素。
如果您的数据模型需要对单调更改的键进行分片,请考虑使用哈希分片
。
原文链接:https://docs.mongodb.com/manual/core/sharding-shard-key/
译者:刘翔
Copyright © 上海锦木信息技术有限公司 all right reserved,powered by Gitbook文件修订时间: 2020-12-18 11:34:57