2013-05-28 65 views
0

我是mongoDB中的新成員,我看到了足夠多的示例,但大多數都展示瞭如何使用集合。如何從mongoDB中的對象獲取字段列表?

下DB名myDB存儲在MongoDB中我按照數據:

"_id" : "some_table_name", 
"content" : [{ 
    "id" : "1", 
    "loctype" : "Clinic/Hospital", 
    "locname" : "KKH" 
}, { 
    "id" : "2", 
    "loctype" : "Clinic/Hospital", 
    "locname" : "Singapore National Eye Centre"  
} 
}] 
} 

正如你所看到的模型包含_idcontent,其中content爲對象的名單:

... , 
{ 
    "id" : "ZZZ", 
    "loctype" : "ZZZ", 
    "locname" : "ZZZ"  
    }, 
    ... 

PHP

$m = new MongoClient(/* ... */); 

$db = $m->myDB; 

$collection = $db->coll; 

如何獲取PHP的ID列表? a.e [1,2]在我的情況。

當然,我可以得到所有模型和提取id,但我嘗試從mongoDB中直接做。

謝謝。

回答

2

這要看你怎麼想這個格式化的,但這裏是格式化它在一個不錯的方式聚集版本:

$mongo->collection->aggregate(array(
    array('$unwind'=>'$content'), 
    array('$project'=>array('_id'=>'$content.id')) 
)) 

這將打印文件,如:

[ 
    {_id:1}, 
    {_id:2} 
] 

另一種方式可能是將單場投射出$db->collection->find(array(),array('content.id'=>1))

但我應該注意到,最好在PHP中這樣做。通過PHP是唯一可以獲得您所尋求的確切輸出的方式,我相信。

+0

所以這是MongoDB的CLI的語法,對不對? –

+0

@MaximShoustin True,轉換爲PHP – Sammaye

+0

Downvoter,小心解釋一下? – Sammaye

2

試試這個:

$collection = new MongoCollection($db, 'collection_name'); 

$query = array(
// Some restrictions can be here 
); 

$ids = array(); 
$cursor = $collection->find($query); 
foreach ($cursor as $doc) { 
    $doc = (array) $doc; 
    $ids[] = $doc["id"]; 
} 

var_dump($ids); 
1

使用的MapReduce其次是不同的,具體如下:

mr = db.runCommand({ 
    "mapreduce" : "things", 
    "map" : function() { 
    for (var key in this) { emit(key, null); } 
    }, 
    "reduce" : function(key, stuff) { return null; }, 
    "out": "things" + "_keys" 
}) 
db[mr.result].distinct("_id") 
["foo", "bar", "baz", "_id", ...] 

或者使用Variety ...

+0

你能說明它是如何工作的我的例子,請? –

相關問題