mongodb: finding the highest numeric value of a column

前端 未结 4 921
闹比i
闹比i 2020-12-19 06:34

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)

相关标签:
4条回答
  • 2020-12-19 07:15

    This works for me

    $options = ['limit' => 100,'skip' => 0, 'projection' => ['score' => ['$meta' => 'textScore']], 'sort' => ['score' => ['$meta' => 'textScore']]];
    
    0 讨论(0)
  • 2020-12-19 07:21

    with PHP driver (mongodb)
    using findOne()

    $filter=[];
    $options = ['sort' => ['age' => -1]]; // -1 is for DESC
    $result = $collection->findOne(filter, $options);
    $maxAge = $result['age']
    
    0 讨论(0)
  • 2020-12-19 07:24

    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);
    
    0 讨论(0)
  • 2020-12-19 07:32

    You can use aggregate function to get maximum number from collections like this.

    $data=$collection->aggregate(array
                        ( '$group'=> 
                            array('_id'=>'',
                                'age'=>array('$max'=>'$age'.)
                            )
                        )
                );
    
    0 讨论(0)
提交回复
热议问题