duanqiang3925 2012-10-20 11:10
浏览 93
已采纳

使用php将mysql查询转换为mongodb

Currently I have an mysql table like this:

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

In this table I store every hit made for a specific media. I save mediaID and date when this hit happened. So ... when I want to show trending medias (most viewed medias for specific time period), I use this mysql query:

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

Now.. I'm planning to move this in MongoDB. Currently I have collection "hits" with the following documents:

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

So, my question is how to convert my previous query to be able to work with MongoDB? P.S. I'm using php with php mongodb driver.

Greetings, Milen

  • 写回答

2条回答 默认 最新

  • dongquan6030 2012-10-20 21:23
    关注

    Use the Aggregation Framework. You want to only count hits from the last 24 hours, group them by mediaID and then order highest to lowest and show top ten, right?

    In the shell:

    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}
    ] )
    

    You will get back for sample data you showed:

    {
        "result" : [
            {
                "mediaID" : "2",
                "cnt" : 2
            },
            {
                "mediaID" : "1",
                "cnt" : 1
            }
        ],
        "ok" : 1
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容