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条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决,来真人,不要ai!
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法