Is there possible to rename collection function for golang driver?

In our project, we got into a problem. When the tokens collection was created it was the only type of tokens in our systems and that didn’t add any issues but now we have internal tokens and external tokens (old tokens collection) this adds confusion. We want to rename and refactor all of the token collection to external tokens and rename the collection during migration, not by hand. But it seems Golang driver of Mongo DB does not support this functionality is there a possibility to create that functionality?

Hey @Mantas_Silanskas welcome and thanks for the question. To run administrative commands like renameCollection with the Go driver, you can use the RunCommand method with a renameCollection command.

E.g. to rename mydb.tokens to mydb.external_tokens:

// renameCollection must be run against the "admin" database,
// even to rename collections in other databases.
db := client.Database("admin")

err := db.RunCommand(context.Background(), bson.D{
	{"renameCollection", "mydb.tokens"},
	{"to", "mydb.external_tokens"},
}).Err()
if err != nil {
	log.Print("Error:", err)
}

Check out the full documentation on the renameCollection command here:

2 Likes

Hello @Matt_Dale and thank you for a fast and great answer.

I just wanted to ask is there a way to do this without:

// renameCollection must be run against the "admin" database,
// even to rename collections in other databases.
db := client.Database("admin")

as most of our clients won’t have access to the admin database?

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.