2

我在 MongoDB 中有以下数据结构:

{ "_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 脚本中从每窝幼犬中提取最年轻的幼犬。

但我不确定这是否能正常工作。关于如何正确执行此操作的任何想法(不更改数据结构)?

4

1 回答 1

1

您可以使用 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);
?>
于 2012-11-30T20:22:58.377 回答