MongoDB选择排序问题

时间:2012-11-15 02:23:37

标签: php android mysql sql mongodb

我的问题是我想做一个数据库查找(选择)witz一个分区排序。 ^^

在我的代码中看起来像:

$return = $db->selectCollection( $category )->find(array("time" > $time_lastweek))->sort(array("rating/count_raitings" => 1,"count_raitings" => 1))->limit(10);

我之前在SQL(PDO)中这样做过:

$last_week = $dbh->prepare('SELECT * FROM '.$category.' WHERE time > :zeit ORDER BY rating/count_raitings ASC, count_raitings ASC LIMIT 10');
        $last_week->execute(array(':zeit' => $time_lastweek));
        $return = $last_week->fetchAll(PDO::FETCH_CLASS);

任何人都可以帮助我。 MongoDB的东西对我不起作用。

1 个答案:

答案 0 :(得分:2)

以下是如何使用aggregation framework在shell中执行此操作(应该直接转换为PHP):

db.category.aggregate([
    // Filter the docs to those where time > time_lastweek
    { $match: {time: {$gt: time_lastweek}}},

    // Identify what to include from each doc, adding a computed field for the division
    { $project: {
        time: 1,
        rating: 1,
        count_raitings: 1,
        div_val: {$divide: ['$rating', '$count_raitings']}
    } },

    // Sort the results
    { $sort: {div_val: 1, count_raitings: 1}},

    // Limit to the top 10
    { $limit: 10 }
])