4

The only way I found to do this is:

$mongo->selectDB('new_db')->createCollection('tmp_collection');
$mongo->selectDB('new_db')->dropCollection('tmp_collection');

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

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Mongo(); is deprecated now.
2

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?"

1 Comment

Well actually I'm creating my admin UI so I need this feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.