Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
881 views
in Technique[技术] by (71.8m points)

sorting - sort by string length in Mongodb/pymongo

I was wondering if anyone knows how to sort a mongodb find() result by string length.

I have tried something like db.foo.find().sort({item.lenght:-1}) but obviously doesn't work. Can somebody help me and also suggest me a way to do the same thing but in pymongo?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are lot of things ( and basic API ) I would personally love to see in the aggregation framework such as:

Math functions

  • log (as in logarithm)
  • ceil
  • floor

Array

  • sum

String

  • length

Just to name a few.

And that is without resorting to obscure usages of the $mod operator or other means in such cases as "ceil" and "floor". But I digress.

Your "string length" falls into this category. Raise a JIRA issue about it. But for now you you can use mapReduce and the existing JavaScript functionality:

db.collection.mapReduce(
    function() {
        emit( this.item.length, this.item );
    },
    function(key,values) {
        return values;
    },
    { "out": { "inline": 1 } }
)

So while that does actually have the "mapReduce" funky style of returning a re-shaped document and with of course everything matching the same length in an array, what it does do is take advantage of the nature of "mapReduce" ( not just restricted to MongoDB ) and allows the emitted "key" value to be sorted in the response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...