Mongo Aggregation


Mongo Aggregation

我的收藏中有以下文档

{
    "_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"),
}

我需要一个查询来获得每个类别的前五条最新消息。有什么建议吗?

假设您安装了最新版本的mongodb,一种方法是:

  • CCD_ 1在CCD_ 2的基础上按降序排列记录
  • CCD_ 3基于它们的CCD_。对于每个组,将所有记录收集在一个数组中
  • 在javascript/客户端代码中,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,并且依次具有顶部Sort0记录的阵列。

您可以排序,然后限制您的请求。

$top_five_other = iterator_to_array($db->find(array('category'=>'other')->sort(array('published_date'=>-1))->limit(5));

您可以尝试聚合查询

1-db.collection.aggregate({$group:{_id:{category:"$category"},total:{$sum:1}})

db.collection.aggregate({$group:{_id:{category:"$category"},total:{$sum:1}},{$sort:{_id:1})。。forEach(函数(myDoc){打印(myDoc_id.category);

})