conikeec
conikeec

Reputation: 209

Programmatically enable sharding + choosing shard key on a collection using casbah with Mongo 2.4

I am attempting to programmatically "enable sharding" and set the "shard key" using java/scala API particularly casbah

Our config

scala 2.10
casbah 2.6 - "org.mongodb" % "casbah_2.10" % "2.6.0",
MongoDB 2.4.4

Also what is the casbah driver version for mongo 2.4.4 (with scala 2.10)

Our use case is such that, collections + indexes are created programmatically using the casbah scala API dbConnection.getCollection(....) and collection.ensureIndex(DBObject("orgId" -> 1), DBObject("background" -> true, "name" -> "org_idx", "unique" -> false))

Is there an equivalent casbah API to programmatically, enableSharding and choose shardKey as well as we are currently sharding our mongo cluster to scale out. Our database + collection names are not known ahead time and a dynamically created using API, so a enabling sharding using mongo shell is simply not an option.

Is there a better way to do this ? ANy recommendations?

Upvotes: 3

Views: 2591

Answers (2)

Kyrstellaine
Kyrstellaine

Reputation: 442

Here's what worked for me, building on @Ross's answer, which didn't quite work for me:

import com.mongodb.casbah.Imports._

// Connect to MongoDB
val conn = MongoClient()
val adminDB = conn("admin")

// Enable sharding on the DB
adminDB.command(MongoDBObject("enableSharding" -> <database>))

// Create the index for our shard key
val shardKey = MongoDBObject("_id" -> "hashed")
conn(<database>)(<collection>).ensureIndex(shardKey)

// Enable sharding on the collection
adminDB.command(MongoDBObject("shardCollection" -> "<database>.<collection>", 
    "key" -> shardkey))

Upvotes: 1

Ross
Ross

Reputation: 18111

For completeness and to help others - enableSharding is a command (see the enableSharding docs) and you can run any command from casbah by using db.command.

import com.mongodb.casbah.Imports._

// Connect to MongoDB
val conn = MongoClient()
val adminDB = conn("admin")


// Enable sharding
adminDB.command(MongoDBObject("shardCollection" -> "<database>.<collection>", "key" -> <shardkey>))

The part should be a MongoDBObject defining the shardkey.

As Asya mentions this might not be the right solution for your use case but its certainly possible to do pragmatically using casbah.

Upvotes: 0

Related Questions