I can do it easily on mysql
select * from TABLE order by length(FIELD) asc
How can I do it on MongoDB?
I can do it easily on mysql
select * from TABLE order by length(FIELD) asc
How can I do it on MongoDB?
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}}
]
)
"field"
key must refer to an extant field in the document, and explain that the "field_length"
key is customizable, since it's calculated on demand.)
Commented
Mar 24, 2020 at 19:42
"errmsg" : "$strLenCP requires a string argument, found: missing",
Commented
Apr 15, 2020 at 2:46
$addFields
operator rather than the first $project
operator, as it will retain all existing fields in addition to adding the new one. {$addFields: { "field_length": {$strLenCP: "$field"}}}
Commented
Jul 19, 2021 at 18:02
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