Mongodb使用$ substr按字段分组 [英] Mongodb group by field using $substr
问题描述
我有一个查询来按文件名分组.
I have an query to group by file name. Something like
db.images.aggregate([ <query> ,
{ $group: { _id: { $substr: [ "$FileName", 3, -1 ] }, files: { $push: "$$ROOT" } } },
{ $sort: { UploadDate : -1 } }
])
我需要在子字符串函数中将起始索引设置为第一个匹配符号"_".
"$FileName.indexOf('_')"
之类的东西.有人可以帮我吗?
I need to set start index in substring function to first match symbol "_".
Something like "$FileName.indexOf('_')"
. Could anyone help me?
推荐答案
There is a dirty but working solution based on this link http://www.kamsky.org/stupid-tricks-with-mongodb/ugly-way-to-parse-a-string-with-aggregation-framework So, why not?
要在字符串中找到符号位置,我们可以构建一个复杂的条件来依次检查字符串中的每个符号是否匹配.它基本上类似于indexOf函数的工作原理.
To find a symbol position in the string, we can build a complex condition to sequentally check each symbol of the string for matching symbol. It is basically similar to how indexOf function works.
function indexOf(field, character) {
var array = [];
var maxPos = 50;
var searchStart = 0;
array[maxPos]={"$cond":{"if":{"$eq":[{"$substr":[field,maxPos,1]},character]},"then":maxPos+1,else:0}};
for ( var i=maxPos-1; i>searchStart-1; i-- ) {
array[i]={"$cond":{"if":{"$eq":[{"$substr":[field,i,1]},character]},"then":i,"else":array[i+1]}}
}
return array[searchStart];
}
因此,您的MongoDB请求将如下所示:
So, your MongoDB request will look like this:
db.images.aggregate([ <query> ,
{ $group: { _id: { $substr: ["$FileName", indexOf("$FileName", "_"), 999] }, files: { $push: "$$ROOT" } } },
{ $sort: { UploadDate : -1 } }
])
这篇关于Mongodb使用$ substr按字段分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!