dunn less
dunn less

Reputation: 623

mongodb wildcard query from grails/groovy

I’m having some problems with issuing a wildcard query in MongoDB from my Grails application.

Basically the way I am doing it now is by issuing a find query with an array of query parameters:

db.log.find(criteria)    -> where criteria is an array [testId:"test"]

This works fine as long as I’m strictly querying on actual values. However, for fun, I tried it with a wildcard search instead:

db.log.find(criteria) -> this time critera = [testId:/.*te.*/]

This however will after looking at the Mongo query log as:

 query: { query: { testId: "/.*te.*/" }

hence making the query not a wildcard search, but a query for this as a string, instead. Is there a way to work around this in some sense still using this concept of querying?

Thanks in advance!

Upvotes: 0

Views: 1707

Answers (3)

BrentR
BrentR

Reputation: 928

This worked for me: In your groovy file:

db.collectionName.find([fieldName:[$regex:'pattern']])

More or less, use a regular mongodb query, but replace the {} with [].

Upvotes: 1

Huuu
Huuu

Reputation: 492

Use the Groovy Pattern shortcut ~ to specify that your query is a regular expression.

db.log.find(['testId': ~/.*te.*/])

See this blog post for more info

Upvotes: 3

coderLMN
coderLMN

Reputation: 3076

To use regex query, define query condition with $regex operator

def regexCondition = ['$regex': '/.*te.*/']
def criteria = ['testId': regexCondition]
db.log.find(criteria)

Upvotes: 1

Related Questions