2015-10-23 77 views
2

這裏字符串我創建了一個集合與單個文檔MongoDB的GET _id作爲查找查詢

db.getCollection('example').insert({"example":1}); 

我曾嘗試使用投影,和我回去了_id。

db.getCollection('example').find({"example":1},{"_id":1}); 

{ 
    "_id" : ObjectId("562a6300bbc948a4315f3abc") 
} 

但是,我需要下面的輸出如下所示。

  1. ID,而不是與 「562a6300bbc948a4315f3abc」

    { "id" : "562a6300bbc948a4315f3abc" }

雖然我可以在我的應用程序服務器上處理#1和#2 _id

  • 的ObjectId( 「562a6300bbc948a4315f3abc」)(基於PHP)來獲得所需的輸出,我期待是否有辦法從mongo本身查詢預期結果

  • 回答

    1

    您需要使用.aggregate()方法。

    db.getCollection('example').aggregate([ { "$project": { "_id": 0, "id": "$_id" } } ]); 
    

    其中產量:

    { "id" : ObjectId("562a67745488a8d831ce2e35") } 
    

    或使用.str財產。

    db.getCollection('example').find({"example":1},{"_id":1}).map(function(doc) { 
        return {'id': doc._id.str } 
    }) 
    

    將返回:

    [ { "id" : "562a67745488a8d831ce2e35" } ] 
    

    那麼,如果你使用的是PHP驅動,你可以做這樣的事情:

    $connection = new MongoClient(); 
    $db = $connection->test; 
    $col = $db->example; 
    $cursor = $col->find([], ["_id" => 1]); 
    foreach($cursor as $doc) { print_r(array("id" => $doc["_id"])); } 
    

    其中產量:

    Array 
    (
        [id] => MongoId Object 
         (
          [$id] => 562a6c60f850734c0c8b4567 
         ) 
    
    ) 
    

    或者再次使用MongoCollection::aggregate米ethod。

    $result = $col->aggregate(array(["$project" => ["id" => "$_id", "_id" => 0]])) 
    

    然後,使用foreach循環:

    Array 
    (
        [_id] => MongoId Object 
         (
          [$id] => 562a6c60f850734c0c8b4567 
         ) 
    
    ) 
    
    +0

    謝謝。我不確定在PHP mongo驅動程序中是否支持cursor.map。有什麼想法嗎? –

    +0

    在我的問題中提到,我能夠在獲得光標句柄後在PHP上處理1和2。但我的問題是從mongo本身檢索[{「id」:「562a67745488a8d831ce2e35」}] –

    +0

    好的。感謝#1解決了。 #2仍然開放 –

    1

    一種簡單的解決方案上PHP側橫穿MongoCursor是使用發電機以及foreacharray_map($function, iterator_to_array($cursor))。 例子:

    function map_traversable(callable $mapper, \Traversable $iterator) { 
        foreach($iterator as $val) { 
         yield $mapper($val); 
        } 
    } 
    

    您可以在PHP documentation about generators syntax滿足更多。因此,現在您可以使用/重用它(或類似的實現),以便在任何數量的映射(就像管道在aggregate中那樣)「投影」PHP數據上的數據,但迭代次數較少。這種解決方案對於重複使用您的map函數的OOP非常方便。

    UPD: 只是爲了下面的案例:

    $cursor = $db->getCollection('example')->find(["example":1],["_id":1]); 
    $mapper = function($record) { 
        return array('id' => (string) $record['_id']); //see \MongoId::__toString() 
    } 
    $traversableWithIdAsStringApplied = map_traversable($mapper, $cursor); 
    //... 
    

    現在你可以應用到$ traversableWithIdAsStringApplied更多的映射進行或只使用iterator_to_array簡單數組檢索。