蒙戈聚合 [英] Mongo Aggregation

查看:68
本文介绍了蒙戈聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的收藏中有以下文档

{
    "_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 条最新消息.有什么建议吗?

I need one query to get top 5 latest news from each category.any suggestions?

推荐答案

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

Assuming you have the latest version of mongodb installed, one way of doing it is:

  • Sort 根据 published_date 降序排列记录.
  • group 基于记录的category.对于每个组,将所有记录收集到一个数组中.
  • 在javascript/客户端代码中,切片每个组(类别)的前5条记录.
  • Sort the records based on the published_date in descending order.
  • group the records based on their category. For each group, collect all the records together in an array.
  • In the javascript/client side code, slice the top 5 records, of each group(category).

$slice 在服务器端 $project 聚合管道操作符中不可用,它阻止我们在服务器端执行操作.

The $slice is not available in the server side $project aggregation pipeline operator, which holds us from performing the operation on the server side.

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 记录的数组.

The result variable will now be an array of documents. Each document representing each category and in turn having an array of top 5 records.

这篇关于蒙戈聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆