6

Is there in MongoDB/mongoose 'like' statement such as in SQL language? The single reason of using is a implementation of full-text searching.

2
  • There's a new and much better way to too accomplish this in MongoDB Atlas using Lucene: docs.atlas.mongodb.com/atlas-search Commented Dec 8, 2020 at 3:04
  • you can find your ans here: stackoverflow.com/a/71136307/14229690 Commented Apr 30, 2022 at 17:18

5 Answers 5

7

MongoDB supports RegularExpressions.

Sign up to request clarification or add additional context in comments.

Comments

2

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));

Comments

2

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.

Comments

0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.