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);
Community
  • 1
  • 1
MoienGK
  • 4,544
  • 11
  • 58
  • 92

2 Answers2

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);
Sean Reilly
  • 21,526
  • 4
  • 48
  • 62
sebastian
  • 2,427
  • 4
  • 32
  • 37
  • thnx. u mean i should write : Pattern regex = Pattern.compile("/.*m.*/"); if i want to find titles which contains "m" ? – MoienGK May 09 '12 at 13:56
  • 2
    @dave you can simply write Pattern regex = Pattern.compile("m"); – sebastian May 09 '12 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) – Sean Reilly May 09 '12 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 May 09 '12 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. – Sean Reilly May 09 '12 at 14:12
  • @sean hmmmm, so what choice do i have to implement somthing like db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); in java ?? id my way depricated? – MoienGK May 09 '12 at 15:30
  • @dave It looks like your current approach is the right way for that problem. – Sean Reilly May 09 '12 at 15:33
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));
hestellezg
  • 3,309
  • 3
  • 33
  • 37