Sort by string length in Mongodb / pymongo

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

I tried something like db.foo.find().sort({item.lenght:-1}) but obviously does not work. Can someone help me and also offer me a way to do the same thing, but in pymongo?

+6
source share
3 answers

There are many things (and a basic API) that I personally love to see in the aggregation structure, for example:

Math functions

  • log (as in the logarithm)
  • Ceil
  • floor

Array

  • the amount

Line

  • Length

Just to name a few.

And this does not resort to the obscure customs of the $mod operator or other means in such cases as "ceil" and "floor". But I'm distracted.

Your "string length" falls into this category. Raise a JIRA question about this. But now you can use mapReduce and existing JavaScript functions:

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

So, while in fact they have a mapReduce funky style that returns a re-issued document and, of course, all that matches the same array length, what it does is use the nature of β€œmapReduce” ( not limited to MongoDB only) and allows you to emit a "key" value in the response.

+6
source

Now in MongoDB v3.4 + there is a solution using the aggregation structure using $ strLenBytes . Given the following document:

 {_id: 0, name: "Bob"} 

We can use

 db.mycollection.aggregate([{ $project: { byteLength: {$strLenBytes: "$name"} } }]) 

Which will return 3 for the number of bytes.

+3
source

No, actually this is not possible. I was dealing with a similar problem, I did to save the string length of each object as a property of the object itself. This circumvented the problem.

If you think that this will be implemented (I do it), I recommend that you transfer the problem to JIRA, which for some reason does not have so many votes:

https://jira.mongodb.org/browse/SERVER-5319

0
source

All Articles