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);
7
  • thnx. u mean i should write : Pattern regex = Pattern.compile("/.*m.*/"); if i want to find titles which contains "m" ?
    – MoienGK
    Commented May 9, 2012 at 13:56
  • 2
    @dave you can simply write Pattern regex = Pattern.compile("m");
    – sebastian
    Commented May 9, 2012 at 13:57
  • +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) Commented May 9, 2012 at 13:58
  • 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
    – MoienGK
    Commented May 9, 2012 at 14:02
  • @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. Commented May 9, 2012 at 14:12
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));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.