mongodb组,根据条件获取行

时间:2017-10-09 09:32:55

标签: mongodb aggregation-framework

我有一张表posts,如下所示:

+------+--------+-----------+---------+------------+
| id   | title  | category  | visits  | content    |
+------+--------+-----------+---------+------------+
| 1    | aaa    | 1         | 44      | Text co... |
| 2    | bbb    | 1         | 63      | Text co... |
| 3    | ccc    | 2         | 42      | Text co... |
| 4    | ddd    | 2         | 65      | Text co... |
| 5    | eee    | 2         | 73      | Text co... |
| 6    | fff    | 3         | 57      | Text co... |
| 7    | ggg    | 3         | 79      | Text co... |
| 8    | hhh    | 3         | 62      | Text co... |
| 9    | iii    | 2         | 46      | Text co... |
| 10   | jjj    | 4         | 64      | Text co... |
| 11   | kkk    | 4         | 76      | Text co... |
+------+--------+-----------+---------+------------+

我正在尝试获取每个类别中访问次数最多的帖子以及ID,标题和内容等数据。

通过以下查询,我可以获得每个类别的条目

db.posts.aggregate([
    {"$group": {
        "_id": "$category", 
        "count": {"$sum": 1},
        "max-visits": { $max: "$visits" }
    }}
]);

我能够获得该类别以及该类别的最多访问者和其中的帖子。但我也要求具有最多访问次数的帖子的ID,标题和内容。

预期产出:

    +------+--------+----------------+---------+------------+
    | id   | title  | category(_id)  | visits  | content    |
    +------+--------+----------------+---------+------------+
    | 1    | bbb    | 1              | 63      | Text co... |
    | 2    | eee    | 2              | 73      | Text co... |
    | 3    | ggg    | 3              | 79      | Text co... |
    | 4    | kkk    | 4              | 76      | Text co... |
    +------+--------+----------------+---------+------------+

实际输出:

    +-----------------+--------+-------------+
    | category(_id)   | count  | max-visits  |
    +-----------------+--------+-------------+
    | 1               | 2      | 63          |
    | 2               | 4      | 73          |
    | 3               | 3      | 79          |
    | 4               | 2      | 76          |
    +-----------------+--------+-------------+

1 个答案:

答案 0 :(得分:1)

您应该在$sort之前$group然后轻松获取$first文档的字段。

db.posts.aggregate([
{"$sort": { category: 1, visits: -1 }},
{"$group": {
    "_id": "$category", 
    "count": {"$sum": 1},
    "max-visits": { $max: "$visits" },
    "doc_id": { $first: "$_id" },
    "title": { $first: "$title" },
    "content": { $first: "$content" }
}}
]);