mongodb:查找列的最高数值

2022-01-20 00:00:00 mongodb find php

我有包含多个字段的 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);

相关文章