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

Charles
  • 50,943
  • 13
  • 104
  • 142
Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103

1 Answers1

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).*")
Community
  • 1
  • 1
Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103