mongodb:查找列的最高数值

mar*_*tti 6 php find mongodb

我有包含几个字段的MongoDB文档集合.其中一列/字段应仅为数字,但其中一些字段包含非数字(损坏)数据作为字符串值.我应该找到该列的最高数值,不包括损坏的非数值数据.我知道在MongoDB中获取列的最高值的问题,但AFAIK,这个扩展的案例没有涵盖.

以下示例描述了该问题.对于最高值,"age": 70应返回文档:

[
{
    "id": "aa001",
    "age": "90"
},
{
    "id": "bb002",
    "age": 70
},
{
    "id": "cc003",
    "age": 20,
}
]
Run Code Online (Sandbox Code Playgroud)

为find()/ findOne()查询提供PHP示例会有很大帮助.非常感谢!

JohnnyHK提出了完美的解决方案.这是有效的PHP代码:

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

Joh*_*yHK 7

您可以在查询中使用$type运算符$not来排除文档age字符串.在shell中,您的查询将如下所示:

db.test.find({age: {$not: {$type: 2}}}).sort({age: -1}).limit(1)
Run Code Online (Sandbox Code Playgroud)

或者来自Martti的PHP:

$cursor = $collection->find(array('age' => array('$not' => array('$type' => 2))), array('age' => 1));
$cursor->sort(array('price' => -1))->limit(1);
Run Code Online (Sandbox Code Playgroud)


Alb*_*t s 6

用PHP驱动程序(mongodb)
使用findOne()

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