I can do it easily on mysql
select * from TABLE order by length(FIELD) asc
How can I do it on 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.
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.
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.
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}}
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With