Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'SQL 'like' statement in mongodb [duplicate]

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

like image 348
Erik Avatar asked May 29 '12 05:05

Erik


People also ask

How do I write a like statement in MongoDB?

We can implement the functionality of the like query in Mongo DB by using the find() function in the format – db. collection. find(). We can specify the string, regex, or regular expression for matching the values in the parameters of the find() function.

How do I use wildcards in MongoDB query?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

Is the command in MongoDB that is equivalent of SQL's truncate?

Remove All Documents If you don't specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL's truncate command.

Which command in MongoDB is equivalent to SQL select?

An SQL SELECT statement typically retrieves data from tables in a database, much like a mongo shell find statement retrieves documents from a collection in a MongoDB database.


3 Answers

MongoDB supports RegularExpressions.

like image 130
xdazz Avatar answered Oct 16 '22 00:10

xdazz


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));
like image 40
Coe Lnt Avatar answered Oct 16 '22 00:10

Coe Lnt


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.

like image 2
Zaid Masud Avatar answered Oct 16 '22 02:10

Zaid Masud