1

Ok, the idea is this:

Given a model such as:

Release {

   Work[] works = ....

}

and

Work {

   String title;

}

I get how to search for Releases using as criteria "has a Work with title=whatever":

DBObject crit = new BasicDBObject();
crit.put("works", new BasicDBObject("$elemMatch",new BasicDBObject("title", "whatever")));

I also get how to use regex for basic stuff, such as "get all Works which have a tile containing whatever":

crit.put("title", "/.*whatever.*/");

But how do I go about doing something like "get all Releases which have a Work with title that CONTAINS whatever" ?

If I try this, I get nothing:

crit.put("works", new BasicDBObject("$elemMatch",new BasicDBObject("title", "/.*whatever.*/")));

Thanks

1 Answer 1

8

Well, ok, I had pretty much the same issue as the one presented in this question:

MongoDB Regex Query : Why doesn't this work?

Basically if, using the Java driver, you put your regular expression such as

new BasicDBObject("title", "/.*whatever.*/")

it will not work (though their documentation and the mongo console test sais it should)

however, if you use the more verbose way of declaring your regex criteria, it will work:

crit.put("works", new BasicDBObject("$elemMatch",new BasicDBObject("title",new BasicDBObject("$regex",".*whatever.*"))));

It get's even messier. If you want your regex pattern to be applied case-insensitively, adding the $options:'i' name value pair to the regex criteria object such as:

new BasicDBObject("$regex",".*whAteVer.*").put("$options","i")

will not work either.

Instead you have to put the insensitivity regex flag INSIDE your regex string like this:

new BasicDBObject("$regex",".*((?i)whAteVer).*")
Sign up to request clarification or add additional context in comments.

Comments

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.