按Mongodb/pymongo中的字符串长度排序 [英] sort by string length in Mongodb/pymongo
问题描述
我想知道是否有人知道如何按字符串长度对mongodb find()
结果进行排序.
I was wondering if anyone knows how to sort a mongodb find()
result by string length.
我尝试了类似db.foo.find().sort({item.lenght:-1})
的方法,但是显然不起作用.有人可以帮我,也可以建议我用pymongo做同样事情的方法吗?
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?
推荐答案
我个人会喜欢在聚合框架中看到很多东西(和基本API),例如:
There are lot of things ( and basic API ) I would personally love to see in the aggregation framework such as:
- log(以对数形式)
- ceil
- 地板
- 总和
- 长度
仅举几例.
并且在不使用 $mod
运算符或其他手段(例如天花板"和地板")的情况下,这是不可行的.但是我离题了.
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.
您的字符串长度"属于这一类.提出有关此问题的JIRA问题.但是,现在您可以使用 mapReduce 和现有的JavaScript功能:>
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 } }
)
因此,尽管实际上确实具有返回重新整形的文档的"mapReduce"时髦风格,并且当然所有内容都与数组中的相同长度匹配,但是它所做的是利用了"mapReduce"的本质(不仅限于MongoDB),还允许在响应中对发出的键"值进行排序.
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.
这篇关于按Mongodb/pymongo中的字符串长度排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!