我正在使用 mongodb 做项目。所以在这里我编写了单独的函数来创建数据库。这是我的代码
$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();
但在创建数据库后它没有显示。但是如果我像这样添加记录,
$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();
它显示了数据库。是什么原因请帮助我。