mongodb 手动分片的命令汇总
手动分片的操作
自动分片会带来性能的下降. 所以要合理使用手动分片. 并且配合Tag一起使用.
# 对于4个shard的程序, 预先处理的指令
1. 加入分片服务器
sh.addShard( "192.168.1.60:27017" )
sh.addShard( "192.168.1.61:27017" )
sh.addShard( "192.168.1.62:27017" )
sh.addShard( "192.168.1.63:27017" )
2. 启动collection分片, 并指定分片键
db.location.ensureIndex({"hostid":1})
sh.enableSharding("mydb")
sh.shardCollection("mydb.location", { "hostid": 1})
运行 sh.status()
{ "_id" : "mydb", "partitioned" : true, "primary" : "shard0003" }
mydb.location
shard key: { "hostid" : 1 }
chunks:
shard0003 1
{ "hostid" : { "$minKey" : 1 } } -->> { "hostid" : { "$maxKey" : 1 } } on : shard0003 Timestamp(1, 0)
sh.addShardTag("shard0000", "TAG0")
sh.addShardTag("shard0001", "TAG1")
sh.addShardTag("shard0002", "TAG2")
sh.addShardTag("shard0003", "TAG3")
# 具体操作
1. 加入tagrange,
加入两个
sh.addTagRange("mydb.location", { hostid: "0000000" }, { hostid: "3100000" }, "TAG0")
sh.addTagRange("mydb.location", { hostid: "3100000" }, { hostid: "3200000" }, "TAG1")
由于当前的primary位 shard0003,
sh.addTagRange("mydb.location", { hostid: "3200000" }, { hostid: "3300000" }, "TAG2")
sh.addTagRange("mydb.location", { hostid: "3300000" }, { hostid: "3500000" }, "TAG3")
sh.addTagRange("mydb.location", { hostid: "3500000" }, { $maxKey: 1 }, "TAG3")
4. add chunck
// 将primary 放到第二个分片上
db.runCommand({movePrimary:"mydb",to:"shard0001"})
查看分片情况
db.chunks.find({ns:"mydb.location"})
手动建立空的chunk
for ( var x=300; x<350; x++ ){
var prefix = String(x*10000);
sh.splitAt( "mydb.location", { "hostid":prefix } )
}
然后移动chunk到对应的地方, 移动chunk的命令
sh.moveChunk("mydb.location", { hostid: "3000000"}, "shard0000")
==shard0000
for ( var x=300; x<310; x++ ){
var prefix = String(x*10000);
sh.moveChunk( "mydb.location", { "hostid":prefix }, "shard0000" )
}
==shard0001 310 - 320
==shard0002 320 - 330
==shard0003 330 - 350
其他一些查询操作
// 查找大于 340000的数据, 并且
db.chunks.find({ns:"mydb.location", min:{$gte:{ "hostid" : "3400000" }}})
db.getSiblingDB("admin").runCommand( { moveChunk : "mydb.location" ,
find : { "hostid" : "3400000" } ,
to : "shard0003" } )
1. 建立索引
use mydb
db.location.ensureIndex({"hostid":1})
db.location.ensureIndex({"posTime":1})
db.location.ensureIndex({"hostno":1})
db.location.createIndex( { loc : "2dsphere" } )
db.location.ensureIndex({"posTime":1,"loc":"2dsphere"})
db.location.ensureIndex({"posTime":1,"hostno":1,"loc":"2dsphere"})
db.location.getIndexes()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具