2013-05-28 66 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

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

相关问题