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?
Solution 1:
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}}
]
)
Post a Comment for "How To Sort Results By String Length On Mongodb"