Is there in MongoDB/mongoose 'like' statement such as in SQL language? The single reason of using is a implementation of full-text searching.
-
There's a new and much better way to too accomplish this in MongoDB Atlas using Lucene: docs.atlas.mongodb.com/atlas-search – Nice-Guy Dec 08 '20 at 03:04
-
you can find your ans here: https://stackoverflow.com/a/71136307/14229690 – Sahil Thummar Apr 30 '22 at 17:18
5 Answers
Two ways we can implement regular expression using java API for mongodb:
Expression 1: I need to search start with that string in document field
String strpattern ="your regular expression";
Pattern p = Pattern.compile(strpattern);
BasicDBObject obj = new BasicDBObject()
obj.put("key",p);
Example : (consider I want to search wherever name start with 'a')
String strpattern ="^a";
Pattern p = Pattern.compile(strpattern);
BasicDBObject obj = new BasicDBObject()
obj.put("name",p);
Expression 2:
I need to search multiple words in one field , you can use as follows
String pattern = "\\b(one|how many)\\b";
BasicDBObject obj = new BasicDBObject();
//if you want to check case sensitive
obj.put("message", Pattern.compile(pattern,Pattern.CASE_INSENSITIVE));

- 90,663
- 31
- 146
- 203

- 31
- 4
Although you can use regular expressions, you won't get good performance on full text search because a contains query such as /text/ cannot use an index.
A begins-with query such as /^text/ can, however, use an index.
If you are considering full text search on any large scale please consider MongoDB's Multi Key Search feature.
Update
As of MongoDB v3.2 you can also use a text index.

- 13,225
- 9
- 67
- 88
Consider making a script at application level that transforms your data to tokens (words). Then treat tokens as tags, build an index on those tokens, and then search the tokens like searching for tags. This is like creating an inverted index.
For way better search capabilities on text consider using Lucene instead of MongoDB.

- 559
- 7
- 15
Use regex: /^textforesarc$/i. Just don't forget to say goodbye to performance :). Simulating regex search with like will not hit custom defined index. Only starts with is supported for now.

- 848
- 8
- 22