我正在尝试检查字段的第一个字符是不是a-z
db.zips.aggregate(
[
{ $group : { city: { $regex: '^[a-z]', $options: 'i' }, n : {$sum:1} } }
]
)
这是一个预期会找到的示例文档,但查询错误与未知运算符'$ regex'有关。已安装MongoDB v2.4.5:
{"city": "25536", "loc": [-82.076761, 38.087553], "pop": 61, "state": "WV", "_id": "25536"}
错误:
Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:15)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
at (shell):1:9
Wed Jul 31 12:14:14.737 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: unknown group operator '$regex'",
"code" : 15952,
"ok" : 0
} at src/mongo/shell/collection.js:L898
谢谢!
P.S。我也尝试了这个:
db.zips.aggregate(
[
{ $project : { city: /^[a-z]/i }}
,{ $group : { city : "$city", n : {$sum:1} } }
]
)
Error: Printing Stack Trace
at printStackTrace (src/mongo/shell/utils.js:37:15)
at DBCollection.aggregate (src/mongo/shell/collection.js:897:9)
at (shell):1:9
Wed Jul 31 12:26:21.531 JavaScript execution failed: aggregate failed: {
"errmsg" : "exception: disallowed field type RegEx in object expression
(at 'city')",
"code" : 15992,
"ok" : 0
} at src/mongo/shell/collection.js:L898
看来,我尝试使用正则表达式的方法不正确或者位置/操作不正确。
答案 0 :(得分:2)
$ regex不能在那里使用,你想看这样的JIRA:https://jira.mongodb.org/browse/SERVER-8892
但是,我认为您实际上希望通过正则表达式而不是组来$match
。所以你想要符合你标准中的所有城市,然后你想把它们分组。
这里提到的是一个重复的问题,我刚刚通过谷歌搜索找到:using $regex in mongodb aggregation framework in $group