【问题标题】:Get top 5 documents with newest nested objects获取包含最新嵌套对象的前 5 个文档
【发布时间】:2012-11-30 19:38:36
【问题描述】:

我在 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 脚本中获取拥有最小幼犬的五窝,然后从每窝中提取最小的幼犬。

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

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    您可以使用 MongoDB 2.2 中的新 Aggregation Framework 来实现此目的:

    <?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);
    ?>
    

    【讨论】:

    • 注意:aggregate() 助手是在 PHP 1.3.0 驱动程序版本中添加的。您仍然可以通过传递管道 using a command() 与旧版本的驱动程序进行聚合。
    • 太棒了 - 非常感谢您的精彩详细回答!
    猜你喜欢
    • 2016-09-18
    • 2021-02-13
    • 2018-07-28
    • 2020-01-08
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多