2

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

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

这是我的代码。

            $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 数据库?

4

3 回答 3

1

复制数据库(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);

删除数据库(php + mongodb):

<?php

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

print_r($response);
于 2013-02-05T08:04:20.037 回答
0

you can use this

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

$mongo->admin->command($query);
于 2013-12-17T16:29:12.230 回答
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 ) 
于 2013-08-21T21:40:46.850 回答