使用PHP和MongoDB根据关键字and值对结果进行排序


Using PHP and MongoDB sorting results based on key AND value?

在我的例子中,我使用MongoDB存储来自50个国家的一大堆产品,DB中的条目看起来像这样:

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

我想知道是否可以从auFIRST查询所有产品并按国家/地区排序,然后再查询其他产品。简单的MongoDB排序似乎只按关键字排序。如果可能的话,它是否涉及映射/减少?

编辑:更详细的示例

收集文件:

{ 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'},

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

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

简单的MongoDB排序似乎只根据密钥进行排序

真是无知的胡说八道。

MongoDB可以根据多种标准进行排序。简单看一下基本对文档进行排序在这里会很有用。

http://www.mongodb.org/display/DOCS/Sorting+和+自然+订单