Create a MongoDB Database Using PHP

The only way I found this is:

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

Doing just $mongo->selectDB('new_db') doesn't actually work. Any ideas?

+4
source share
2 answers

You will need to run at least one command in the database before creating it ...

This command can be run before you add any collections ... so that you can simply list (non-existent) collections.

 <?php $connection = new Mongo(); $db = $connection->foo; $list = $db->listCollections(); foreach ($list as $collection) { echo "$collection </br>"; } ?> 

Your new database will now exist until user-created collections are created.

+10
source

Technically, you don’t need to manually create databases or collections in MongoDB because of your β€œlazy” way of creating databases and collections.

I understand that you came from the world of SQL, it does not make much sense. You might want to ask yourself: "If he automatically creates a collection or database for me on the fly, is it really necessary to define it ahead of time?"

+2
source

Source: https://habr.com/ru/post/1333026/


All Articles