2013-02-25 49 views
5

我有MongoDB包含多个字段的文档集合。其中一个列/字段应仅为数字,但其中一些字段包含非数字(损坏)的数据作为字符串值。我应该找到该栏的最高数值,排除损坏的非数值数据。我知道Getting the highest value of a column in MongoDB这个问题,但是AFAIK,这个扩展案例没有涉及。mongodb:找到列的最高数值

下面的例子描述了这个问题。对于最高值,并"age": 70文档应返回:

[ 
{ 
    "id": "aa001", 
    "age": "90" 
}, 
{ 
    "id": "bb002", 
    "age": 70 
}, 
{ 
    "id": "cc003", 
    "age": 20, 
} 
] 

提供查找()/ findOne()查询将有很大帮助一个PHP的例子。非常感谢!

JohnnyHK提出了完美的解决方案。这里的工作PHP代码:

$cursor = $collection->find(array('age' => array('$not' => array('$type' => 2))), array('age' => 1)); 
$cursor->sort(array('age' => -1))->limit(1); 

回答

7

您可以使用$type运营商,$not在查询中排除文档,其中age是一个字符串。在外壳查询看起来像:

db.test.find({age: {$not: {$type: 2}}}).sort({age: -1}).limit(1) 

或者在PHP从马尔蒂:

$cursor = $collection->find(array('age' => array('$not' => array('$type' => 2))), array('age' => 1)); 
$cursor->sort(array('price' => -1))->limit(1); 
+0

哇真快,谢谢!完美的作品。我将添加工作相关的PHP代码到问题中。 – martti 2013-02-25 17:54:30

0

可以使用聚合函数从这样的藏品获得最大数量。

$data=$collection->aggregate(array 
        ('$group'=> 
         array('_id'=>'', 
          'age'=>array('$max'=>'$age'.) 
         ) 
        ) 
      ); 
3

用PHP驱动程序(MongoDB的)
使用findOne()

$filter=[]; 
$options = ['sort' => ['age' => -1]]; // -1 is for DESC 
$result = $collection->findOne(filter, $options); 
$maxAge = $result['age'] 
0

这对我的作品

$options = ['limit' => 100,'skip' => 0, 'projection' => ['score' => ['$meta' => 'textScore']], 'sort' => ['score' => ['$meta' => 'textScore']]];