Mongodb的java driver本身的接口
void createCollection(String collectionName, CreateCollectionOptions createCollectionOptions)
是不支持創建一個sharding collection的,通過此方式創建的collection不支持分片,即此表存放在一個節點上。傳統的方式是通過mongodb的shell命令(見之前的文章),如
sh.shardCollection("dbname.tablename", {"_id": "hashed"}) to create a shard table hashed by _id
但是這種方式也有一定的制約,不能通過程序動態的添加表,如果我默認的表不足以支撐業務,就必須通過shell方式創建一個sharding表,之后再插入數據才能滿足要求。
通過javadoc的查詢,MongoDatabase存在如下接口:
Document runCommand(Bson command)
也就是說,通過此接口可以執行runCommand命令。而runCommand命令是什么呢?通過官方reference(https://docs.mongodb.com/manual/reference/command/shardCollection/)的查詢,我們看到如下說明:
Shards a collection to distribute its documents across shards. You must run enableSharding on a database before running the shardCollection command. The shardCollection command must be run against the admin database. To run shardCollection, use the db.runCommand( { <command> } ) method. shardCollection has the following form: { shardCollection: "<database>.<collection>", key: <shardkey>, unique: <boolean>, numInitialChunks: <integer>, collation: { locale: "simple" } }
也就是說,我們可以通過shell命令,執行db.runCommand({shardCollection:"db.collection", key: {"_id": "hashed"}})來執行此命令。
對於java driver而言,我們只要把命令中的json當參數調用runCommand應當就可以實現創建sharding表了。
接下來看java driver的接口,傳遞參數是一個Bson,之前我們進行查詢以及過濾時生成過Bson,不過那些model顯然不全,只是為了查詢方便Mongodb幫我們建好的,里面並不包含shardCollection。於是去javadoc找到對應的Bson:
http://mongodb.github.io/mongo-java-driver/3.4/javadoc/
里面有
Interface Bson
找到此Interface后看下面有哪些類implement了此接口。
Class BasicDBObject
接下來去此BasicDBObject頁面看看怎么用就可以了,具體實現方式為:
lazy val mongoURI = new MongoClientURI(new MongoUserUtils().origin2URI) lazy val mongo = new MongoClient(mongoURI) //這里必須是admin,只有admin庫才有創建shardingcollection的權限。 lazy val db = mongo.getDatabase("admin") val bs = new BasicDBObject() bs.append("shardCollection", "test.testsharding2") bs.append("key", mapAsJavaMap(Map(("_id", "hashed")))) println(bs.toJson()) db.runCommand(bs)