seriousdev
seriousdev

Reputation: 7656

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')->dropCollection('tmp_collection');

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

Upvotes: 4

Views: 9626

Answers (2)

Justin Jenkins
Justin Jenkins

Reputation: 27080

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.

Upvotes: 10

Joshua Burns
Joshua Burns

Reputation: 8572

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

Upvotes: 2

Related Questions