Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...