1

I have a MongoDB, I can query the database with 'Country' that works fine. But I now want to also search on the field 'title' with free text. As with in SQL the WHERE title LIKE '%title%'

BasicDBObject query = new BasicDBObject();
query.put("country", country);
query.put("title", %title%);
DBCursor cursor = collection.find(query);

How would I do this with MongoDB?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Marc Stevens
  • 353
  • 2
  • 4
  • 11

3 Answers3

4

You can use regular expressions In your case, /title/i should work (as MySQL like query is usually case-insensitive, /i denotes case-insensitive match)

Maxim Krizhanovsky
  • 26,265
  • 5
  • 59
  • 89
  • Thanks! How would I put this into my code? BasicDBObject query = new BasicDBObject(); query.put("country", country); query.put("title", /title/i); ??????????? – Marc Stevens Aug 23 '11 at 08:08
0

Use this this pattern is java regular expression

Pattern title = Pattern.compile("title");
BasicDBObject dbc=new BasicDBObject();
dbc.put("title", title );
DBCursor cursor = collection.find(query);

This will work,.. try it

Sadesh Kumar N
  • 1,962
  • 7
  • 19
  • 26
0

if you got the keyword in variable...

Model.find( { FIELD_NAME : { $regex: KEYWORD, $options: 'i' }});

and if you got the keyword as just a string...

Model.find( { FIELD_NAME : /string/i });

should work like SELECT * FROM Model WHERE FIELD_NAME LIST = KEYWORD.

'i' toggles case-insensivity, so that you can search the word with no case exception.

hina10531
  • 3,938
  • 4
  • 40
  • 59