Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
seriousdev Avatar asked Dec 17 '22 18:12

seriousdev


1 Answers

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.

like image 106
Justin Jenkins Avatar answered Jan 03 '23 03:01

Justin Jenkins