4

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?

1 Answer 1

5

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";
?>
Sign up to request clarification or add additional context in comments.

Comments

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.