Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database in mongoDB using php

Tags:

php

mongodb

I am on mongoDB 3 and php version 5.6. I want to create a database for adding data in it. I am trying in this way.

<?php

    require 'vendor/autoload.php';

   // connect to mongodb

   $db = new MongoDB\Client("mongodb://localhost:27017");

   echo "Connected";

   // select a database
   $data = $db->selectDatabase("admin");

   echo "Done ";
?>

This code is running well but not making any database in the MongoDB. Can someone help?

like image 733
Amar Avatar asked Oct 28 '25 15:10

Amar


1 Answers

I hope you have installed Mongodb driver for PHP and you are not receiving any exception while executing your code.

After the db connection is established you need to save something in collection so that the db comes to existence. This is missing in your code.

Try below code

<?php
   // connect to mongodb
   $m = new MongoClient();

   echo "Connection to database successfully";
   // select a database
   $db = $m->admin;
   echo "Database admin selected";

   $collection = $db->createCollection("mycol");
   echo "Collection created succsessfully";
?>
like image 72
Robin Varghese Avatar answered Oct 31 '25 05:10

Robin Varghese



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!