mongos> use testdb
switched to db testdb
mongos> db.mycoll.insertOne({id: 1, "test": "test_shard"})
{
"acknowledged" : true,
"insertedId" : ObjectId("5c039517071e1ba7e339fe24")
}
# 首先要让数据库启动分片
mongos> sh.enableSharding("testdb")
{
"ok" : 1,
"operationTime" : Timestamp(1543738671, 3),
"$clusterTime" : {
....
}
mongos> db.mycoll.find({})
{ "_id" : ObjectId("5c039517071e1ba7e339fe24"), "id" : 1, "test" : "test_shard" }
# 因为集合不为空,所以在执行shardCollection前要先创建索引,如果集合为空,会自动创建索引
mongos> db.mycoll.createIndex({id: 1})
{
"raw" : {
"shard1/127.0.0.1:27003" : {
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
},
...
}
# 查看索引
mongos> db.mycoll.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "testdb.mycoll"
},
{
"v" : 2,
"key" : {
"id" : 1
},
"name" : "id_1",
"ns" : "testdb.mycoll"
}
]
# 使用 _id 作为分片键
mongos> sh.shardCollection("testdb.mycoll", {_id:1})
{
"collectionsharded" : "testdb.mycoll",
"collectionUUID" : UUID("cffb9588-52df-4df4-bb1a-9e461602cabd"),
"ok" : 1,
...
}
# 因为先使用 _id 作为分片键,再使用 id 会报错
mongos> sh.shardCollection("testdb.mycoll", {id:1})
{
"ok" : 0,
"errmsg" : "sharding already enabled for collection testdb.mycoll with options { _id: \"testdb.mycoll\", lastmodEpoch: ObjectId('5c039722733b2ba5a2bafebd'), lastmod: new Date(4294967296), dropped: false, key: { _id: 1.0 }, unique: false, uuid: UUID(\"cffb9588-52df-4df4-bb1a-9e461602cabd\") }",
"code" : 23,
"codeName" : "AlreadyInitialized",
...
}
# 插入100000条数据
mongos> for (var i = 1; i <= 100000; i++) db.mycoll.save({id:i,"test1":"test_shard"});
WriteResult({ "nInserted" : 1 })
# 查看结果(不知道是不是因为分片键为_id的缘故,数据并没有分散到shard2中)
mongos> db.mycoll.stats()