用PHP实现MongoDB查询中的订单
使用php时,如何在MongoDB查询中排序用PHP实现MongoDB查询中的订单,php,mongodb,Php,Mongodb,使用php时,如何在MongoDB查询中排序 $regexObj = new MongoRegex('/'.$str.'/i'); $search = array('title' => $regexObj); $cursor = $this->collection->find($search); 我在MongoDB中有一个字段作为表,其中包含行: //first [title] => Great Musuem [table] => arts //secon
$regexObj = new MongoRegex('/'.$str.'/i');
$search = array('title' => $regexObj);
$cursor = $this->collection->find($search);
我在MongoDB中有一个字段作为表,其中包含行:
//first
[title] => Great Musuem
[table] => arts
//second
[title] => Musuem
[table] => people
//third
[title] => Garden
[table] => arts
//4th
[title] => Garden
[table] => music
etc ...
我应该如何使用一张表格按照人们先来,然后是艺术,然后是音乐的顺序进行排序
例如:
[title] => Musuem
[table] => people
[title] => Great Musuem
[table] => arts
[title] => Garden
[table] => arts
[title] => Garden
[table] => music
您必须在客户端进行排序,因为MongoDB没有非线性排序功能。PHP中的一个简单usort()将为您完成以下任务:
<?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 );
?>
我试图避免循环和正常的php排序,以提高性能。但若这个特性不存在,那个么我不得不回到php排序。谢谢你的回答……是的,你必须在客户机上这样做!