如何在MongoDB上按字符串长度对结果排序 [英] How to sort results by string length on MongoDB
本文介绍了如何在MongoDB上按字符串长度对结果排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以轻松地在mysql上完成
I can do it easily on mysql
select * from TABLE order by length(FIELD) asc
我如何在MongoDB上做到这一点?
How can I do it on MongoDB?
推荐答案
MongoDB 3.4引入了$strLenCP
聚合运算符,该运算符终于支持了此运算符.一个例子:
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}},
]
)
这篇关于如何在MongoDB上按字符串长度对结果排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文