重命名mongo数据库

时间:2013-02-05 06:24:06

标签: php mongodb

我正在使用mongodb和php做项目。所以我在这里尝试使用php重命名现有数据库。所以我按照以下方式重命名数据库。

  • 首先我创建新数据库(用户新数据库名称)
  • 读取旧数据库的所有记录并插入新数据库
  • 然后我放弃旧db

这是我的代码。

            $conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
            $exist_dbs = $conn->listDBs();

            foreach ($exist_dbs["databases"] as $databse) {
                if ($databse['name'] == $new_name) {
                    $new_name_is_exist = true;
                }
            }
            if (!$new_name_is_exist) {
                $db = new \MongoDB($conn, $old_name);

                //create new database
                $db_new = new \MongoDB($conn, $new_name);
                $collections = $db->getCollectionNames();

                foreach ($collections as $collection) {
                    //create collection
                    $new_collection = new \MongoCollection($db_new, $collection);

                    $mongo_collection = $db->$collection;
                    $objects = $mongo_collection->find();

                    while ($document = $objects->getNext()) {
                        //add records
                        $new_collection->insert($document);
                    }
                }
                $db->drop();
                $msg = 'database renamed';
            } else {
                $msg = 'given database name already exist';
            }
            $conn->close();

它工作正常。但我想知道有没有更好的方法来使用php重命名mongo数据库?

3 个答案:

答案 0 :(得分:1)

复制db(php + mongodb):

<?php

$rename = 'oldname';
$name = 'newname';
$mongo = (new MongoClient());
$db = $mongo->admin;
$response = $db->command(array(
    'copydb' => 1, 
    'fromhost' => 'localhost',
    'fromdb' => $rename,
    'todb' => $name
    ));

print_r($response);

删除db(php + mongodb):

<?php

$name = 'oldname';
$mongo = (new MongoClient());
$db = $mongo->$name;
$response = $db->command(array(
    'dropDatabase' => 1
    ));

print_r($response);

答案 1 :(得分:0)

$db=new new Mongo();

将old_db复制到new_db

$responseCopy = $db->admin->command(array(
    'copydb' => 1, 
    'fromhost' => 'localhost',
    'fromdb' => 'old_db',
    'todb' =>'new_db'
    ));

现在删除old_db

if($responseCopy['ok']==1){
 $responseDrop=$db->old_db->command(array('dropDatabase' => 1));
 //OR 
 $responseDrop =$db->old_db->drop();
}

显示输出

print_r($responseCopy);
print_r($responseDrop);

输出将是这样的

Array ( [ok] => 1 ) 
Array ( [dropped] => old_db [ok] => 1 ) 

答案 2 :(得分:0)

你可以用这个

$mongo = new MongoClient('_MONGODB_HOST_URL_');
$query = array("renameCollection" => "Database.OldName", "to" => "Database.NewName", "dropTarget" => "true");

$mongo->admin->command($query);