2012-11-30 23 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