1

I am trying to rename a database using MongoMapper in ruby. Is it possible to do the same? any alternative hack to accomplish the same?

2

1 Answer 1

2

As noted in the other stack overflow question mentioned above, MongoDB doesn't actually have the ability to rename a database. You can however, copy then delete but be aware this will cause indexes to be rebuilt. You wouldn't want to do this for a large data set.

The mongo-ruby-driver (as well as most 10gen drivers) has the ability to execute any MongoDB command through a call to the DB#command method on any DB object instance.

In the Ruby driver you would do the following:

require 'mongo'
client = Mongo::MongoClient.new
db = client.db('admin')

db.command({:copydb => 1, :fromdb => oldname, :todb => newname})
client.drop_database(oldname)

Update: In newer versions of MongoDB there is a JS shell helper for db.rename() which does exactly what the ruby code above does.

function (newName) {
  if(newName == this.getName() || newName.length === 0)
    return;

  this.copyDatabase(this.getName(), newName, "localhost");
  this.dropDatabase();
  db = this.getSiblingDB(newName);
}

In addition to that, there is the following feature request ticket for making db.rename() a first class command. Please feel free to upvote this feature.

https://jira.mongodb.org/browse/SERVER-701

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.