mongodb: finding the highest numeric value of a column(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:查找列的最高数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:mongodb:查找列的最高数值
基础教程推荐
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01