使用基于关键AND值的PHP和MongoDB排序结果?

时间:2012-01-18 02:49:22

标签: php sorting mongodb mapreduce

对于我的情况,我使用MongoDB存储来自50个国家/地区的大量产品,DB中的条目看起来像这样:

{
    _id: xxxxxxxxxxxxxxx,
    country: 'au',
    title: 'Equipment X',
    price: 1000,
},
{
    _id: xxxxxxxxxxxxxxy,
    country: 'us',
    title: 'Equipment Y',
    price: 1000,
},
...
...

我想知道是否可以查询所有产品并按国家/地区分类 au FIRST,然后是其他产品。简单的MongoDB排序似乎只按键排序。如果有可能,它是否涉及map / reduce?

编辑:更详细的示例

收藏中的文件:

{ country:'cn', title:'Equipment A', price:'100'},
{ country:'au', title:'Equipment B', price:'100'},
{ country:'za', title:'Equipment C', price:'100'},
{ country:'us', title:'Equipment D', price:'100'},
{ country:'nz', title:'Equipment E', price:'100'},
{ country:'it', title:'Equipment F', price:'100'},
{ country:'nz', title:'Equipment G', price:'100'},
{ country:'au', title:'Equipment H', price:'100'},

我正在寻找一种将 nz 的产品返回到顶部然后跟随所有其他产品的类别,如下所示:

{ country:'nz', title:'Equipment E', price:'100'},
{ country:'nz', title:'Equipment G', price:'100'},
{ country:'au', title:'Equipment B', price:'100'},
{ country:'au', title:'Equipment H', price:'100'},
{ country:'cn', title:'Equipment A', price:'100'},
{ country:'it', title:'Equipment F', price:'100'},
{ country:'us', title:'Equipment D', price:'100'},
{ country:'za', title:'Equipment C', price:'100'},

2 个答案:

答案 0 :(得分:2)

通过对键进行排序,它意味着对键中的值进行排序。我想这就是你想要的。 (从开头部分开始连接到数据库并选择一个集合。)

$cursor = $collection->find();
$cursor->sort(array('country' => 1))

更新这就是您想要做的事情吗?

$cursor = $collection->find(array('country' => 'nz'));
// process your nz products...

$cursor = $collection->find(array('country' => array( '$neq' => 'nz' )));
// process the rest of your products...

update2 好吧,如果您确实需要此功能,我认为您可能需要采取类似的措施。

// create a new field on the records that don't have it yet
$collection->update(
   array('country' => 'nz', array('first' => array('$exists' => false))), 
   array('$set' => array('first'=>1)), 
   array('multiple' => true));
// ensure index on that field
$collection->ensureIndex(array('first' => 1));
// find everything
$cursor = $collection->find();
// sort on that field
$cursor->sort(array('first':-1));

答案 1 :(得分:0)

  

简单的MongoDB排序似乎只按键排序

真正无知的废话。

MongoDB可以按多个条件排序。简单看一下基本的 排序文档在这里很有用。

http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order