Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Selection Sort Issue

my problem is i want to do a Database find (Selection) witz a division in sort. ^^

That looks in my Code like:

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

I have done this before in SQL (PDO) like this:

$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);

Please can anyone help me. The MongoDB thing wont work for me.

like image 206
MCSell Avatar asked Mar 14 '26 05:03

MCSell


1 Answers

Here's how you could use the aggregation framework to do it in the shell (should be straightforward to translate to 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 }
])
like image 194
JohnnyHK Avatar answered Mar 16 '26 17:03

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!