Search code examples
mongodbgomgo

MongoDB shardCollection command in Go


I'm trying to shard a collection using mgo library in Go. Looks like I can't figure out to run commands using Session.Run call. Here is my code:

if err := session.DB("admin").Run(bson.D{{"shardCollection", "visits.visits-2016-05"}, {"uuid", "1"}}, &result); err != nil {
    panic(err)
} else {
    fmt.Println(result)
}

I've tried several variants of passing key parameter, but I'm always getting no shard key error

What am I doing wrong here?


Solution

  • I think the issue you're having is that you have to specify that the second field is the key of key and the value is the subdocument of {uuid: 1}. This way you're matching the exact fields listed by the mongo documentation: https://docs.mongodb.org/manual/reference/command/shardCollection/.

    The code I'm using for the same process is:

    if err := adminDb.Run(
                bson.D{
                    {
                        "shardCollection",
                        "logs.log_"+dateString,
                    },
                    {
                        "key",
                        bson.M{
                            "sk": "hashed",
                        },
                    },
                }, &result); err != nil {
                    log.Println("Failed to shardCollection logs.log_"+dateString, err)
                }
    

    So you might want to try

    if err := session.DB("admin").Run(bson.D{{"shardCollection", "visits.visits-2016-05"}, {"key", bson.M{"uuid", "1"}}}, &result); err != nil {
        panic(err)
    } else {
        fmt.Println(result)
    }