2012-07-12 32 views
2

獲取數據這是我在MongoDB中從集合中獲取數據的PHP代碼:如何從命名組集合MongoDB中使用PHP代碼

$m = new Mongo('localhost'); 
$m->connect(); 
$db = $m->mydb; 
$collection = $db->fields_current; 
$cursor = $collection->find(); 
foreach ($cursor as $obj) { 
    echo $obj["title"] . "\n"; 
} 

的代碼工作正常進行採集fields_current。但是,我有這樣一個集合fields_current.node其中node是集合的命名組。如何從指定的組中獲取數據。

編輯:

以下PeterM的回答後,我收到一個空MongoCursor對象。這是我的新代碼:

$m = new Mongo('localhost'); 
$m->connect(); 
$db = $m->mydb; 
$collection = $db->fields_current; 
$query = array(array('group_name' => 'node', 'type' => 'content-type'), array('title' => 1)); // SELECT title FROM fields_current WHERE group_name = 'node' AND type = 'content-type' 
$cursor = $collection->find($query); 
foreach ($cursor as $obj) { 
    echo $obj["title"] . "\n"; 
} 

更多的細節:我使用Drupal和node指的是「節點」表,type是「節點式」。該集合名稱爲fields_current.node和記錄的結構是這樣的:

array (
    '_id' => new MongoInt32(37), 
    '_type' => 'node', 
    '_bundle' => 'content-type', 
    '_revision_id' => new MongoInt32(37), 
    'nid' => new MongoInt32(37), 
    'vid' => new MongoInt32(37), 
    'type' => 'content-type', 
    'language' => 'und', 
    'title' => 'title', 
    'uid' => new MongoInt32(1), 
    'status' => new MongoInt32(1), 
    'created' => new MongoInt32(1342065549), 
    'changed' => new MongoInt32(1342065549), 
    'comment' => new MongoInt32(1), 
    'promote' => new MongoInt32(0), 
    'sticky' => new MongoInt32(0), 
    'tnid' => new MongoInt32(0), 
    'translate' => new MongoInt32(0), 
    'field_cutom_field' => 
    array (
    'value' => 'foobar', 
), 
) 

回答

1

自Drupal的,你不必指定數據庫名稱,當你寫的查詢只喜歡爲MySql。另外還有一個獲取集合對象的函數。

// Suppose you have a collection called 'collection_name', then you can get its object using this code. 
$collection = mongodb_collection('collection_name'); 

// Suppose you have a collection called 'collection_name.group', where 'group' is the named group of this collection, then you can get its object using this code. 
$collection = mongodb_collection('collection_name', 'group'); 

// Rest of the operations will be same. 
$cursor = $collection->find(array('type' => 'content-type')); 
foreach ($cursor as $obj) { 
    .... 
    // Do your work... 
    .... 
} 
2
$cursor = $collection->find(array('node' => 'group_name')); 

http://www.php.net/manual/en/mongo.sqltomongo.php更多的例子

+0

但它返回一個空的MongoCursor對象。如何從那裏獲取字段。我提到了文檔,看起來像我缺少一些東西。我對mongodb很陌生。 – subhojit777 2012-07-13 05:28:20

+0

查詢是查找的第一個參數,而字段是第二個參數。你做了一個數組。它應該是'$ collection-> find($ query,$ fields);'所以它應該是'$ query = array('group_name'=>'node','type'=>'content-type');'' (注意:你沒有字段group_name,它應該是_type?)還是'$ fields = array('title')' – 2012-07-13 08:39:17

相關問題