我在 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 脚本中从每窝中提取最小的小狗。
但我不确定这是否会正常工作。关于如何正确执行此操作(不更改数据结构)的任何想法?
最佳答案
您可以使用新的 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);
?>
关于php - 获取包含最新嵌套对象的前 5 个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651941/