DATADOC-146 added overloaded regex method taking options parameter

This commit is contained in:
Thomas Risberg
2011-06-01 10:14:22 -04:00
parent 25b9a56030
commit 134996d079
3 changed files with 60 additions and 0 deletions

View File

@@ -29,6 +29,7 @@ import org.springframework.data.document.mongodb.geo.Box;
import org.springframework.data.document.mongodb.geo.Circle;
import org.springframework.data.document.mongodb.geo.Point;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
public class Criteria implements CriteriaDefinition {
@@ -271,6 +272,21 @@ public class Criteria implements CriteriaDefinition {
return this;
}
/**
* Creates a criterion using a $regex and $options
*
* @param re
* @param options
* @return
*/
public Criteria regex(String re, String options) {
criteria.put("$regex", re);
if (StringUtils.hasText(options)) {
criteria.put("$options", options);
}
return this;
}
/**
* Creates a geospatial criterion using a $within $center operation
*

View File

@@ -575,6 +575,36 @@ public class MongoTemplateTests {
}
}
@Test
public void testUsingRegexQueryWithOptions() throws Exception {
template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class);
PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId();
p1.setFirstName("Sven");
p1.setAge(11);
template.insert(p1);
PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId();
p2.setFirstName("Mary");
p2.setAge(21);
template.insert(p2);
PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId();
p3.setFirstName("Ann");
p3.setAge(31);
template.insert(p3);
PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId();
p4.setFirstName("samantha");
p4.setAge(41);
template.insert(p4);
Query q1 = new Query(Criteria.where("firstName").regex("S.*"));
List<PersonWithIdPropertyOfTypeObjectId> results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class);
Query q2 = new Query(Criteria.where("firstName").regex("S.*", "i"));
List<PersonWithIdPropertyOfTypeObjectId> results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class);
assertThat(results1.size(), is(1));
assertThat(results2.size(), is(2));
}
@Test
public void testUsingAnOrQuery() throws Exception {

View File

@@ -130,4 +130,18 @@ public class QueryTests {
String expected = "{ \"state\" : { \"$in\" : [ \"NY\" , \"NJ\" , \"PA\"]}}";
Assert.assertEquals(expected, q.getQueryObject().toString());
}
@Test
public void testQueryWithRegex() {
Query q = new Query(where("name").regex("b.*"));
String expected = "{ \"name\" : { \"$regex\" : \"b.*\"}}";
Assert.assertEquals(expected, q.getQueryObject().toString());
}
@Test
public void testQueryWithRegexandOption() {
Query q = new Query(where("name").regex("b.*", "i"));
String expected = "{ \"name\" : { \"$regex\" : \"b.*\" , \"$options\" : \"i\"}}";
Assert.assertEquals(expected, q.getQueryObject().toString());
}
}