简体   繁体   中英

Doesn't show created mongodb

I am doing project using mongodb. so here I wrote separate functions to create db. this is my code

            $conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
            $exist_dbs = $conn->listDBs();

            foreach ($exist_dbs["databases"] as $databse) {
                if ($databse['name'] == $db_name) {
                    $is_exist = true;
                }
            }

            if (!$is_exist) {
                $db = new \MongoDB($conn, $db_name);
                $status = true;
                $msg = 'database successfully created';

            } else {
                $status = false;
                $msg = 'database already exist';
            }
            $conn->close();

but after create db it didn't show. but if I add record to that like this,

            $conn = new \MongoClient('mongodb://example.com:27017', array("connect" => TRUE));
            $exist_dbs = $conn->listDBs();

            foreach ($exist_dbs["databases"] as $databse) {
                if ($databse['name'] == $db_name) {
                    $is_exist = true;
                }
            }

            if (!$is_exist) {
                $db = new \MongoDB($conn, $db_name);
                $status = true;
                $msg = 'database successfully created';
                //new code
                $collection = new \MongoCollection($db, 'users');
                $obj = array("name" => "Madawa", "age" => "34");
                $collection->insert($obj);
            } else {
                $status = false;
                $msg = 'database already exist';
            }
            $conn->close();

it shows the database. what is the reason please help me.

When you say

$db = new \MongoDB($conn, $db_name);

You aren't creating a database, you are creating an object that can access a database. It doesn't mean the database does exist or that it makes it, just that you now have an object capable of accessing it. So you've basically said "Make me a database object to handle my calls and I'd like to select $db_name" but that is all that has happened. The database doesn't exist until you put something into it or perform some action on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM