How to sort results by string length on MongoDB

左心房为你撑大大i 提交于 2020-01-01 02:30:08

问题


I can do it easily on mysql

select * from TABLE order by length(FIELD) asc

How can I do it on MongoDB?


回答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}},
    ]
)



回答2:


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.

Syntax

The basic syntax of sort() method is as follows −

db.COLLECTION_NAME.find().sort({KEY:1})

Example

Consider the collection myycol has the following data.

{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Untitled"}

Following example will display the documents sorted by title in the descending order.

db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Untitled"}
{"title":"NoSQL"}
{"title":"MongoDB"}

Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order.




回答3:


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



来源:https://stackoverflow.com/questions/15471718/how-to-sort-results-by-string-length-on-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!