2012-11-30 22 views
2

我在MongoDB的數據結構如下:獲得前5名的文件與最新的嵌套對象

{ "_id" : ObjectId("xy"), 
    "litter" : [ 
    { "puppy_name" : "Tom", 
     "birth_timestamp" : 1353963728 }, 
    { "puppy_name" : "Ann", 
     "birth_timestamp" : 1353963997 } 
    ] 
} 

我有很多具有不同的小狗的數量,這些「垃圾」文件。時間戳數字越高,小狗越年輕(=後來出生)。

我想要做的是從所有垃圾文件中檢索五個最小的小狗。

我試過的東西沿着

find().sort('litter.birth_timestamp' : -1).limit(5) 

拿到五胎具有最年輕的小狗,然後從中提取在PHP腳本每窩最年輕的小狗。

但我不確定這是否會正常工作。任何想法如何做到這一點(沒有改變數據結構)?

回答

1

您可以使用新的Aggregation Framework MongoDB中2.2來實現這一點:

<?php 
    $m = new Mongo(); 
    $collection = $m->selectDB("test")->selectCollection("puppies"); 

    $pipeline = array(

     // Create a document stream (one per puppy) 
     array('$unwind' => '$litter'), 

     // Sort by birthdate descending 
     array('$sort' => array (
      'litter.birth_timestamp' => -1 
     )), 

     // Limit to 5 results 
     array('$limit' => 5) 
    ); 

    $results = $collection->aggregate($pipeline); 
    var_dump($results); 
?> 
+0

注意:'骨料()輔助函數是在PHP 1.3.0驅動程序版本添加。您仍然可以通過傳遞管道[使用'command()'](http://stackoverflow.com/questions/11290809)與舊版驅動程序進行聚合。 – Stennie

+1

太好了 - 非常感謝你的答覆! – Goeran