GibboK GibboK - 1 month ago 6x
Javascript Question

MONGO DB Like Operator

I'm using JavaScript to query an API based on a Mongo DB.

I would need filter the result based on LIKE operator, something similar to

select * from playlist where title like '%a%'

At the moment I call this URL

var assetUrl = '' + accessToken + '&account=XXX'+ '&fields={"title":true,"splash":true,"description":true,"source":true}'+ '&criteria={"title":/.*a.*/}';

With no success (Return 0 objects).

I would like to know if I should use Regular Expressions instead and how to use them in this context. Thanks


Yes, MongoDB supports regular expressions. You can read about it in the documentation. Here is an example:

db.collection.find( { url: /.*a.*/ } );

This finds all documents in the collection where the field "url" matches the regular expression. There is also an alternative syntax using the $regex operator:

db.collection.find( { url: { $regex: ".*a.*"} } );

Note that regular expressions are slow and scale badly. The search time is linear to the number of records in the collection, and indices only help when your regular expression begins with a begin-of-string anchor ^ (thanks, chx).

The documentation also has a chapter about Full Text Search in Mongo which recommends to split each string into an array of individual words, so that you can index it for faster lookup. This of course doesn't allow to search for word fragments, but greatly speeds up search for complete words.

Update: MongoDB 2.4 has a new experimental text-index feature which allows to speed up text-search with indices.

Update2: As of version 2.6, text search is enabled by default and ready for productive use.