Justin John
Justin John

Reputation: 9616

Order in MongoDB query with PHP

How do you order in MongoDB queries when using php?

$regexObj = new MongoRegex('/'.$str.'/i');

$search = array('title'  => $regexObj);

$cursor = $this->collection->find($search);

I have one field as a table in MongoDB with rows:

//first
[title] => Great Musuem
[table] => arts

//second    
[title] => Musuem
[table] => people

//third     
[title] => Garden
[table] => arts

//4th   
[title] => Garden
[table] => music

etc ...

How should I sort according above using a table in order where people come first and then arts and then music?

For example:

[title] => Musuem
[table] => people

[title] => Great Musuem
[table] => arts

[title] => Garden
[table] => arts

[title] => Garden
[table] => music

Upvotes: 0

Views: 214

Answers (1)

Derick
Derick

Reputation: 36764

You will have to do the sorting on the client side as MongoDB has no functionality to sorting on a non-linear order. A simple usort() in PHP will do this for you:

<?php
function sortSpecial($a, $b)
{
    $orders = array( 'people' => 1, 'arts' => 2, 'music' => 3 );
    if ($orders[$a['table']] > $orders[$b['table']]) {
        return 1;
    }
    if ($orders[$a['table']] < $orders[$b['table']]) {
        return -1;
    }
    return strcmp($a['title'], $b['title']);
}

// your results, just for this example:
$results = array(
    array('title' => 'Great Museum', 'table' => 'arts'),
    array('title' => 'Museum',       'table' => 'people'),
    array('title' => 'Garden',       'table' => 'arts'),
    array('title' => 'gaarden',      'table' => 'music'),
);

// sort and display, this also sorts titles in the correct alphabetical order
usort( $results, 'sortSpecial' );
var_dump( $results );
?>

Upvotes: 1

Related Questions