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?

7 Answers 7

70

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 literally saved my sanity. I have been searching how to do some negative regex , as the $not operator does not except $regex
6

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.

Comments

4

To make it case insensitive:

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

Comments

2

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);

Comments

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

Comments

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);
    }
}

Comments

-1

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

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

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

1 Comment

Hi Sudheer Kumar Dara, welcome. Please consider adding an explanation and formating the code properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.