'SQL 'like' statement in mongodb [duplicate]
Two ways we can implement regular expression using java API for mongodb:
Expression 1:I need to search start with that string in document field
String strpattern ="your regular expression";Pattern p = Pattern.compile(strpattern);BasicDBObject obj = new BasicDBObject() obj.put("key",p);
Example : (consider I want to search wherever name start with 'a')
String strpattern ="^a";Pattern p = Pattern.compile(strpattern);BasicDBObject obj = new BasicDBObject() obj.put("name",p);
Expression 2:
I need to search multiple words in one field , you can use as follows
String pattern = "\\b(one|how many)\\b";BasicDBObject obj = new BasicDBObject();//if you want to check case sensitiveobj.put("message", Pattern.compile(pattern,Pattern.CASE_INSENSITIVE));
Although you can use regular expressions, you won't get good performance on full text search because a contains query such as /text/ cannot use an index.
A begins-with query such as /^text/ can, however, use an index.
If you are considering full text search on any large scale please consider MongoDB's Multi Key Search feature.
Update
As of MongoDB v3.2 you can also use a text index.