2013-02-25 51 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']]];