Henry Liu
Henry Liu

Reputation: 700

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?

Upvotes: 26

Views: 13114

Answers (2)

Zohar Bar-Yehuda
Zohar Bar-Yehuda

Reputation: 636

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}}
    ]
)

Upvotes: 27

Marco
Marco

Reputation: 209

suppose your schema is something like:

example = {_id: "XXX", text: "YYY"}

db.example.aggregate([
 {$project : {text : 1, length : {$size : "$text"}}}, 
 {$sort : {length : 1}}
]);

I think this will do the job, but only for mongo 2.6 and above

Upvotes: -3

Related Questions