2016-08-18 83 views
0

我是MongoDB的新手,并在Windows上使用它。我创建了一个数据库,然后在那里创建了一个Collection并插入了记录,我正在通过GUI工具RoboMongo检查它是否显示在GUI工具上,但是当我通过代码获取它时,它什么也没有显示。 以下是代码,请指导我该怎么做。PHP MongoClient找不到工作

$m = new MongoClient('mongodb://root:[email protected]'); 
$db = $m->selectDB('db_name'); 
$collection_name = 'collection_name'; 
$db->createCollection($collection_name); 
$get_collection = new MongoCollection($db, $collection_name); 
$data = array(
    '_id' => '1_record', 
    'name' => 'Majid Ali', 
    'designation' => 'Developer' 
); 
$get_collection->insert($data); 
$find = $get_collection->find(); 
print_r($find); 

回答

0

你有什么错误吗? 但我认为选择集合的最好办法是这样的:

try{ 
    // Connecting to server 
    $m = new MongoClient('mongodb://root:[email protected]'); 
}catch(MongoConnectionException $connectionException){ 
    print $connectionException; 
    exit; 
} 
try{ 
    // Getting MongoCollection 

    $db = $m->db_name; 
}catch(MongoException $mongoException){ 
    print $mongoException; 
    exit; 
} 
$collection_name = 'collection_name'; 
$db->createCollection($collection_name); 

//Selected the Collection 
$get_collection= $db->collection_name; 

$data = array(
    '_id' => '1_record', 
    'name' => 'Majid Ali', 
    'designation' => 'Developer' 
); 
try{ 
    // Inserting data into students collection 

    $get_collection->insert($data); 
}catch(MongoCursorException $mongoCursorException){ 
    echo $mongoCursorException; 
    exit; 
} 
$find = $get_collection->find(); 
$array = iterator_to_array($find); 
print_r($array ); 
+0

我也只是尝试这种方法,都返回空MongoCursor对象没有任何错误 –

+0

测试连接到MongoDB的, – Provie9

+0

它插入记录,这些都可以通过RoboMongo GUI工具查看,但是当我使用find时,它什么也没有显示 –