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

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

问题描述

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



下面的例子描述了这个问题。对于最高值,应返回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中,您的查询将如下所示:
$ b

  db.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 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)

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天全站免登陆