11

basically this is my question: How to query MongoDB with "like"?

but i guess all the answers in here are applicable when you are using mongodb shell command line, so what is the equivalent for db.users.find({"name": /.*m.*/}) when we are using java.

here is how i am trying to do

  DBCollection coll = MongoDBUtil.getDB().getCollection("post_details");      
    BasicDBObject query = new BasicDBObject();      
    query.put("price", new BasicDBObject("$gt", 5).append("$lt", 8));
    /*what should i write instead of this line*/ 
            query.put("title", "/.*m.*/");

    DBCursor cur = coll.find(query);

2 Answers 2

14

For this issue you should use a regex as in this example:

BasicDBObject query = new BasicDBObject();
Pattern regex = Pattern.compile("the title you are looking for"); // should be m in your case
query.put("title", regex);
Sign up to request clarification or add additional context in comments.

7 Comments

thnx. u mean i should write : Pattern regex = Pattern.compile("/.*m.*/"); if i want to find titles which contains "m" ?
@dave you can simply write Pattern regex = Pattern.compile("m");
+1 — note that MongoDB will "do the right thing" and perform an efficient search with a regex if possible (basically when the regex has a wildcard only at the end)
using pattern makes it so easy! can i use pattern instead of something like this maybe : query.put("price", new BasicDBObject("$gt", 5).append("$lt", 8)); i am getting greedy for more comfort :D
@dave: Probably not :-(. Even if the query you describe did work, MongoDB wouldn't be able to use an index to resolve it anymore, so it would probably make the query much slower. IMO it's best to restrict regex use to places that you would use a LIKE clause in a SQL query.
|
0

Taking the above example as reference, but using the Filters class:

Pattern regex = Pattern.compile("title you look for");
Bson filter = Filters.eq("nombre", regex));

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.