0

I'm trying to check the 1st character of a field to not be a-z

db.zips.aggregate( 
 [
{ $group : { city: { $regex: '^[a-z]', $options: 'i' }, n : {$sum:1} } }
 ]
)

Here is a sample doc expected to be found but the query errors with unknown operator '$regex'. MongoDB v2.4.5 is installed:

{"city": "25536", "loc": [-82.076761, 38.087553], "pop": 61, "state": "WV", "_id":   "25536"}

Error:

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

Thanks!

P.S. I tried this also:

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

So appears that the ways I'm trying to use regex is incorrect or in the incorrect places/operations.

0

1 Answer 1

2

$regex cannot be used there, you want to watch a JIRA like this: https://jira.mongodb.org/browse/SERVER-8892

However, I think you actually want to $match by the regex instead of group. So you want to match all cities in your criteria and then you wanna group them.

As reference here is a duplicate question I just found by Googling: using $regex in mongodb aggregation framework in $group

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I saw that one but couldn't get anything working so I wanted to focus on $regex but I see it won't work they way I'm trying to use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.