mongodb:找到列的最高数值 [英] mongodb: finding the highest numeric value of a column
问题描述
下面的例子描述了这个问题。对于最高值,应返回age:70
的文档:
$ id $ b $ id $ a
$ age $ $
$ b $ :bb002,
age:70
},
{
id:cc003,
age:20,$ b为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);
解决方案您可以使用
$ type
与$ not
在您的查询中排除age
是字符串的文档。在shell中,您的查询将如下所示:
$ bdb.test.find({age:{ $ not:{$ type:2}}})。sort({age:-1})。limit(1)
或者在Martti的PHP中:
$ cursor = $ collection-> find(array('age '=> array('$ not'=> array('$ type'=> 2))),array('age'=> 1));
$ cursor-> sort(array('price'=> -1)) - > limit(1);
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.
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, } ]
Providing a PHP example for the find() / findOne() query would be of much help. Thanks a lot!
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);
解决方案You can use the
$type
operator with$not
in your query to exclude docs whereage
is a string. In the shell your query would look like:db.test.find({age: {$not: {$type: 2}}}).sort({age: -1}).limit(1)
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屋!