在 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"和floor"等情况下使用 $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屋!