Update
- Deleted my old map / reduce method since I found out (and pointed out to Sammaye) that this changes the structure
- Made my version of exec secondary, since I found out how to do this with renameCollection.
I believe that I have found a solution. It seems that some versions of the PHP driver will work with the administrative database, even if it is not needed. But there is a workaround where the authSource connection parameter is used to change this behavior, so it does not authenticate the administrator database, and instead, the database is your choice. So now my renameCollection function is again a wrapper around the renameCollection command.
The key is to add authSource when connecting. In the code below, $ _ENV ['MONGO_URI'] contains my connection string, and default_database_name () returns the name of the database I want to use auth to.
$class = 'MongoClient'; if( !class_exists($class) ) $class = 'Mongo'; $db_server = new $class($_ENV['MONGO_URI'].'?authSource='.default_database_name());
Here is my old version that used eval, which should also work, although some environments do not allow you to evaluate ( MongoLab gives you a cripple if you don't have a dedicated system). But if you work in a closed environment, this seems like a smart solution.
function renameCollection($old_name, $new_name) { db()->$new_name->drop(); $copy = "function() {db.$old_name.find().forEach(function(d) {db.$new_name.insert(d)})}"; db()->execute($copy); db()->$old_name->drop(); }
Eric Anderson
source share