3

I am new to Mongodb,I have to Shard a Collection Based on Integer, String and Date time shard key, I am able to shard a collection using integer shard key. below is the command,I am using for Range Based Sharding.

mongos> use admin
switched to db admin
mongos> db.runCommand({split:"poc_db.test_sharding",middle:{docId:500}})
{ "ok" : 1 }
mongos> db.runCommand({movechunk:"poc_db.test_sharding",find:{docId:1},to:"shard0000"})
{ "millis" : 7288, "ok" : 1 }
mongos> db.runCommand({movechunk:"poc_barclays.db",find:{docId:500},to:"shard0001"})
{ "millis" : 1709, "ok" : 1 }

So what if docId is String or DateTime value, How to set Range?

Ex: ^^#aaaaaah or 3000-01-01 00:00:00.000

Any solution?

1 Answer 1

0

To shard a MongoDB collection based on a string or datetime shard key using range-based sharding, you need to follow a similar approach as with the integer shard key. The main difference is that you will define the ranges based on the values of the string or datetime field.

Let's assume you have a collection named "myCollection" and want to shard it based on the "shardKey" field, which can be either a string or datetime. Here's how you can achieve range-based sharding for each type:

Shard using a String Shard Key: You can use string ranges to shard the collection based on the "shardKey" field. For example, suppose you want to split the data into three shards based on the first character of the "shardKey":

use admin
db.runCommand({ enablesharding: "myDatabase" })

// Shard using string range "a" to "h"
db.runCommand({ shardcollection: "myDatabase.myCollection", key: { shardKey: "hashed" } })

// Split the collection based on the first character of shardKey
db.runCommand({ split: "myDatabase.myCollection", middle: { shardKey: "d" } })

You can adjust the ranges based on your specific use case and data distribution.

Shard using a DateTime Shard Key: For datetime fields, you need to define ranges based on the datetime values. Here's an example of sharding the collection based on years:

use admin
db.runCommand({ enablesharding: "myDatabase" })

// Shard using datetime range from "2000-01-01" to "2030-01-01"
db.runCommand({ shardcollection: "myDatabase.myCollection", key: { shardKey: 1 } })

// Split the collection based on the year value in shardKey
db.runCommand({ split: "myDatabase.myCollection", middle: { shardKey: ISODate("2010-01-01") } })

Again, adjust the ranges based on your specific date range and data distribution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.