开发者

Create a MongoDB database with PHP

The only way I found to do this is:

$mongo->selectDB('new_db')->createCollection('tmp_collection');
$mongo->selectDB('new_db')->dropColl开发者_开发技巧ection('tmp_collection');

Doing just $mongo->selectDB('new_db') actually doesn't work. Got any idea?


You'll need to run at least one command on the Database before it is created ...

This command can be run before you add any Collections ... so you can merely list (the nonexistent) Collections.

<?php

$connection = new Mongo();
$db = $connection->foo;

$list = $db->listCollections();
foreach ($list as $collection) {
    echo "$collection </br>";       
}

?>

Your new Database should now exist, with no user Collections created yet.


Technically, you don't need to manually create databases or collections in MongoDB due to its schemaless "lazy" way of creating databases and collections.

I understand if you're coming from an SQL world this doesn't make much sense. You may want to ask yourself though, "If it automatically creates a collection or database for me on the fly, is there really a need to define it ahead of time?"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜