0

目前我有一个这样的mysql表:

+---------+----------+------+-----+---------+----------------+
| Field   | Type     | Null | Key | Default | Extra          |
+---------+----------+------+-----+---------+----------------+
| id      | int(11)  | NO   | PRI | NULL    | auto_increment |
| mediaID | int(11)  | NO   |     | NULL    |                |
| date    | datetime | NO   |     | NULL    |                |
+---------+----------+------+-----+---------+----------------+

在这张表中,我存储了为特定媒体制作的每个点击。我保存了媒体 ID 和此点击发生的日期。所以......当我想显示趋势媒体(特定时间段内观看次数最多的媒体)时,我使用这个 mysql 查询:

SELECT  mediaID, COUNT(*) as cnt FROM hits WHERE DATE(date) = CURDATE() - INTERVAL 1 DAY GROUP BY mediaID ORDER BY cnt DESC LIMIT 0,10

现在.. 我打算在 MongoDB 中移动它。目前,我收集了以下文件的“命中”:

{
    _id: ObjectId("50827eaaae1c3ced6c00000f"),
    mediaID: "2",
    ts: ISODate("2012-10-20T13:36:26+03:00")
}
{
    _id: ObjectId("50827ebeae1c3ced6c000010"),
    mediaID: "1",
    ts: ISODate("2012-10-20T13:36:46+03:00")
}
{
    _id: ObjectId("50827ec3ae1c3c6167000008"),
    mediaID: "2",
    ts: ISODate("2012-10-20T13:36:51+03:00")
}

所以,我的问题是如何将我以前的查询转换为能够使用 MongoDB?PS 我正在使用 php 和 php mongodb 驱动程序。

问候,米伦

4

2 回答 2

2

使用聚合框架。您只想计算过去 24 小时的点击次数,按 mediaID 分组,然后从高到低排序并显示前十,对吗?

在外壳中:

today = new Date();
// this gets you yesterday but you can change this to be any time period
cutoff = new Date(today.getYear(), today.getMonth(), today.getDate()-1);
db.hits.aggregate( [
   {$match: {ts: {$gt: cutoff} } },
   {$group: {_id: "$mediaID", cnt: {$sum: 1} } },
   {$project: {mediaID: "$_id", cnt:1, _id:0 } },
   {$sort: { cnt:-1 } },
   {$limit: 10}
] )

您将返回您显示的示例数据:

{
    "result" : [
        {
            "mediaID" : "2",
            "cnt" : 2
        },
        {
            "mediaID" : "1",
            "cnt" : 1
        }
    ],
    "ok" : 1
}
于 2012-10-20T21:23:31.917 回答
0

只是另一个建议。

因为你用intwith mediaID,但是你mediaID在mongodb里面的数据是用的string,所以你应该先用intval()转换数据再存入mediaID

如果您使用string而不是int. 是否可以在 MongoDB 查询中进行转换?

于 2012-10-21T19:00:02.167 回答