How to query mongodb with “like” using the java api?

You must first quote your text and then use the compile to get a regex expression:

q.put("name",  Pattern.compile(Pattern.quote(m)));

Without using java.util.Pattern.quote() some characters are not escaped.

e.g. using ? as the m parameter will throw an exception.


You need to pass an instance of a Java RegEx (java.util.regex.Pattern):

BasicDBObject q = new BasicDBObject();
q.put("name",  java.util.regex.Pattern.compile(m));
dbc.find(q);

This will be converted to a MongoDB regex when sent to the server, as well as any RegEx flags.


To make it case insensitive:

Document doc = new Document("name", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
collection.find(doc);