Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  20] [ 1]  / answers: 1 / hits: 19591  / 12 Years ago, fri, november 30, 2012, 12:00:00

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 = 'https://example.com/playlist?oauth_token=' + 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


More From » mongodb

 Answers
6

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.


[#81699] Thursday, November 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arron

Total Points: 663
Total Questions: 119
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
;