2

Currently I am using java to connect to MONGODB, I want to write this sql query in mongodb using java driver:

select * from tableA where name like("%ab%")

is their any solution to perform the same task through java, the query in mongodb is very simple i know, the query is

db.collection.find({name:/ab/})

but how to perform same task in java

Current I am using pattern matching to perform the task and code is

DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab", 
                                           Pattern.CASE_INSENSITIVE)).get();

but it makes query very slow I think , does a solution exist that does not use pattern matching?

4 Answers 4

1

Can use Regular Expressions. Take a look at the following:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions

Make sure you understand the potential performance impacts!

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

Comments

0
DBObject A = QueryBuilder.start("name").is(Pattern.compile("ab", 
                                       Pattern.CASE_INSENSITIVE)).get();

I think this is one of the possible solution, you need to create index to achieve those.

Comments

0

Why do you fear the regular expressions? Once the expression is compiled they are very fast, and if the expression is "ab" the result is similar to a function that search a substring in a string.

However to do what you need you have 2 possibilities:

  1. The first one, using regular expression, as you mention in your question. And I believe this is the best solution.
  2. The second one, using the $where queries.

With $where queries you can specify expression like these

db.foo.find({"$where" : "this.x + this.y == 10"})
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"})

and so you can use the JavaScript .indexOf() on string fields.

Comments

0

Code snippet using the $regex clause (as mentioned by mikeycgto)

String searchString = "ab";
DBCollection coll = db.getCollection("yourCollection");
query.put("name", 
  new BasicDBObject("$regex", String.format(".*((?i)%s).*", searchString)) );
DBCursor cur = coll.find(query);
while (cur.hasNext()) {
  DBObject dbObj = cur.next();
  // your code to read the DBObject ..       
}

As long as you are not opening and closing the connection per method call, the query should be fast.

Comments

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.