jayanth88
jayanth88

Reputation: 574

How to rename a database using MongoMapper in ruby?

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?

Upvotes: 1

Views: 479

Answers (1)

Brandon Black
Brandon Black

Reputation: 887

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

Upvotes: 2

Related Questions