33

this question is very similar to another post

I basically want to use the mongodb version of the sql "like" '%m%' operator

but in my situation i'm using the java api for mongodb, while the other post is using mongodb shell

i tried what was posted in the other thread and it worked fine

db.users.find({"name": /m/})

but in java, i'm using the put method on the BasicDBObject and passing it into the find() method on a DBCollections object

BasicDBObject q = new BasicDBOBject();
q.put("name", "/"+m+"/");
dbc.find(q);

but this doesn't seem to be working.

anyone has any ideas?

Community
  • 1
  • 1
Khon Lieu
  • 4,295
  • 7
  • 37
  • 39

7 Answers7

69

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.

Brendan W. McAdams
  • 9,379
  • 3
  • 41
  • 31
  • +1 literally saved my sanity. I have been searching how to do some negative regex , as the $not operator does not except $regex – kommradHomer Jul 27 '15 at 15:32
4

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.

Community
  • 1
  • 1
Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
4

To make it case insensitive:

Document doc = new Document("name", Pattern.compile(keyword, Pattern.CASE_INSENSITIVE));
collection.find(doc);
Andres
  • 1,090
  • 14
  • 30
1

In spring data mongodb, this can be done as:

Query query = new Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));
mongoOperation.find(query, Tags.class);
Vaibhav
  • 2,073
  • 4
  • 23
  • 26
1
Document doc = new Document("name", Pattern.compile(keyword));
collection.find(doc);
evan.wang
  • 11
  • 2
0

Might not be the actual answer, ( Executing the terminal query directly )

public void displayDetails() {
    try {
        // DB db = roleDao.returnDB();
        MongoClient mongoClient = new MongoClient("localhost", 5000);
        DB db = mongoClient.getDB("test");
        db.eval("db.test.update({'id':{'$not':{'$in':[/su/]}}},{$set:{'test':'test3'}},true,true)", new Object[] {});
        System.out.println("inserted  ");

    } catch (Exception e) {
        System.out.println(e);
    }
}
M. Gopal
  • 404
  • 4
  • 17
-1

if(searchType.equals("employeeId")) {

query.addCriteria(Criteria.where(searchType).regex(java.util.regex.Pattern.compile(searchValue)));

employees = mongoOperations.find(query, Employee.class, "OfficialInformation"); }