我的藏品中有以下文件
{
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample1",
"slug": "samplenews",
"cat": "sports",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-23T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample2",
"slug": "samplenews2",
"category": "entertaintment",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-22T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample3",
"slug": "samplenews3",
"category": "entertaintment",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-9-22T14:06:57.0Z"),
} {
"_id": ObjectId("54490b8104f7142f22ecc97f"),
"title": "Sample4",
"slug": "samplenews4",
"category": "other",
"desc": "sampletextsampletext",
"published_date": ISODate("2014-10-22T14:06:57.0Z"),
}
我需要一个查询来获取每个类别的前5个最新消息。有哪些建议?
答案 0 :(得分:1)
假设您安装了最新版本的mongodb,其中一种方法是:
Sort
基于published_date
的记录按降序排列。group
基于category
的记录。对于每个组,将所有记录收集在一个数组中。slice
每组(类别)的前5条记录。 $slice
在服务器端$project
聚合管道运算符中不可用,它阻止我们在服务器端执行操作。
var result = db.collection.aggregate(
[
{$sort:{"published_date":-1}},
{$group:{"_id":"$category","values":{$push:"$$ROOT"}}}
]
).map(function(doc){
return {"category":doc._id,"records":doc.values.slice(0,5)};
});
result
变量现在将是一个文档数组。每个文档代表每个category
,并依次包含一系列顶级5
条记录。
答案 1 :(得分:1)
您可以尝试汇总查询
1-db.collection.aggregate({$ group:{_ id:{category:" $ category"},total:{$ sum:1}}},{$ sort:{_ id: 1}})
OR
db.collection.aggregate({$ group:{_ id:{category:" $ category"},total:{$ sum:1}}},{$ sort:{_ id:1} }).. forEach(function(myDoc){ 打印(myDoc._id.category);
})
答案 2 :(得分:0)
您可以排序并限制您的请求。
$top_five_other = iterator_to_array($db->find(array('category'=>'other')->sort(array('published_date'=>-1))->limit(5));