问题描述
请考虑以下示例:
db.article.aggregate(
{ $group : {
_id : "$author",
docsPerAuthor : { $sum : 1 },
viewsPerAuthor : { $sum : "$pageViews" }
}}
);
这将按作者字段分组并计算两个字段.
This groups by the author field and computes two fields.
我具有$ author = FirstName_LastName的值.现在,我不想按$ author分组,而是按共享相同姓氏的所有作者分组.
I have values for $author = FirstName_LastName.Now instead of grouping by $author, I want to group by all authors who share the same LastName.
我尝试使用$ regex对'_'之后的所有匹配字符串进行分组
I tried $regex to group by all matching strings after the '_'
$author.match(/_[a-zA-Z0-9]+$/)
db.article.aggregate(
{ $group : {
_id : "$author".match(/_[a-zA-Z0-9]+$/),
docsPerAuthor : { $sum : 1 },
viewsPerAuthor : { $sum : "$pageViews" }
}}
);
also tried the following:
db.article.aggregate(
{ $group : {
_id : {$author: {$regex: /_[a-zA-Z0-9]+$/}},
docsPerAuthor : { $sum : 1 },
viewsPerAuthor : { $sum : "$pageViews" }
}}
);
推荐答案
实际上,没有提供这种功能的方法,或者我找不到包含该功能的合适版本.我认为这不适用于$ regexp: http://docs.mongodb.org/manual/reference/operator /regex/仅用于模式匹配.
Actually there is no such method which provides this kind of functionality or i could not find the appropriate version which contains it. That will not work with $regexp i think : http://docs.mongodb.org/manual/reference/operator/regex/ it is just for pattern matching.
jira中有一个改进请求: https://jira.mongodb.org/browse/SERVER-6773
There is an improvement request in the jira : https://jira.mongodb.org/browse/SERVER-6773
它处于打开的未解决状态.但是
It is in open unresolved state.BUT
在github中,我发现了这样的讨论: https://github.com/mongodb/mongo/pull/336
in github i found this disscussion: https://github.com/mongodb/mongo/pull/336
如果您检查此提交,请执行以下操作: https://github.com/nleite/mongo/commit/2dd175a5acda86aaad61f5eb9dab83ee19915709
And if you check this commit: https://github.com/nleite/mongo/commit/2dd175a5acda86aaad61f5eb9dab83ee19915709
它或多或少地包含您可能拥有的方法.我并没有真正理解这种改进的状态:在2.2.3中,它不起作用.
it contains more or less exactly the method you likely to have. I do not really get the point of the state of this improvement: in 2.2.3 it is not working .
这篇关于在$ group的mongodb聚合框架中使用$ regex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!