查看集合信息

mongos> show collections
comm
system.profile
test
test1
test2
mongos> db.test2.count()
982334
mongos> 

查看索引

mongos> db.test2.getIndexes()
[
	{
		"v" : 2,
		"key" : {
			"_id" : 1
		},
		"name" : "_id_",
		"ns" : "db3.test2"
	}
]

创建哈希索引

mongos> db.test2.createIndex({"_id":"hashed"})
{
	"raw" : {
		"hdshard3/172.16.254.136:40003,172.16.254.137:40003,172.16.254.138:40003" : {
			"createdCollectionAutomatically" : false,
			"numIndexesBefore" : 1,
			"numIndexesAfter" : 2,
			"ok" : 1
		}
	},
	"ok" : 1,
	"operationTime" : Timestamp(1619664717, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1619664717, 1),
		"signature" : {
			"hash" : BinData(0,"LzzTbOHmN0qOhpkbFNkp9kuqru0="),
			"keyId" : NumberLong("6941260985399246879")
		}
	}
}

哈希索引创建完成之后,马上进行哈希分片。

哈希分片

mongos> sh.shardCollection( "db3.test2", { _id: "hashed" } )
{
	"ok" : 0,
	"errmsg" : "sharding not enabled for db db3",
	"code" : 20,
	"codeName" : "IllegalOperation",
	"operationTime" : Timestamp(1619664844, 4),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1619664844, 4),
		"signature" : {
			"hash" : BinData(0,"lbUFNbAmMyci7N/uEUOdCR2te4E="),
			"keyId" : NumberLong("6941260985399246879")
		}
	}
}

报错提示我们数据库db3没有进行分片。

检查数据库分片

mongos> use config
switched to db config
mongos> db.databases.find()
{ "_id" : "db3", "primary" : "hdshard3", "partitioned" : true, "version" : { "uuid" : UUID("f0278f73-d999-453f-8739-eac30a8bcf9b"), "lastMod" : 1 } }

可以看到db3是已经分过片了。

原因分析: 分片要求整个shard对于非空集合必须都具备索引,而我们进行集合分片时候,primary节点哈希索引创建完了,secondary节点还未创建完,导致分片失败。 出现这种情况一般有两种场景:

  1. 操作过快,secondary还未来得及创建哈希索引。
  2. 存在延迟secondary,可以暂时关闭延迟从库。