mongodb:查找列的最高数值 [英] mongodb: finding the highest numeric value of a column

查看:36
本文介绍了mongodb:查找列的最高数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have MongoDB collection of documents containing several fields. One of the columns/fields should be numeric only, but some of these fields contain non-numerical (corrupt) data as string values. I should find the highest numerical value of this column, excluding the corrupt, non-numerical data. I am aware of the question Getting the highest value of a column in MongoDB, but AFAIK, this extended case was not covered.

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

The example below depicts the issue. For the highest value, the document with "age": 70 should be returned:

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

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

Providing a PHP example for the find() / findOne() query would be of much help. Thanks a lot!

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

JohnnyHK came up with the perfect solution. Here's the working PHP code:

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

推荐答案

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

You can use the $type operator with $not in your query to exclude docs where age is a string. In the shell your query would look like:

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

或者来自 Martti 的 PHP:

Or in PHP from Martti:

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

这篇关于mongodb:查找列的最高数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆