Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort results by string length on MongoDB

I can do it easily on mysql

select * from TABLE order by length(FIELD) asc

How can I do it on MongoDB?

like image 402
Henry Liu Avatar asked Mar 18 '13 07:03

Henry Liu


People also ask

How do I sort values in MongoDB?

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

What is the use of sort () in MongoDB?

MongoDB – sort() Method The sort() method specifies the order in which the query returns the matching documents from the given collection. You must apply this method to the cursor before retrieving any documents from the database.

Does MongoDB support sorting?

Sort and Index UseMongoDB can obtain the results of a sort operation from an index which includes the sort fields. MongoDB may use multiple indexes to support a sort operation if the sort uses the same indexes as the query predicate.


1 Answers

MongoDB 3.4 introduces the $strLenCP aggregation operator that finally supports this. An example:

db.collection.aggregate(
    [
        {$project: {
            "field": 1,
            "field_length": { $strLenCP: "$field" }
        }},
        {$sort: {"field_length": -1}},
        {$project: {"field_length": 0}}
    ]
)
like image 168
Zohar Bar-Yehuda Avatar answered Nov 04 '22 11:11

Zohar Bar-Yehuda