MongoDB Database, query with LIKE
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?
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)
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
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.
精彩评论