Monday, July 18, 2011

MongoDB + regular expressions

In traditional SQL databases, one could do a LIKE query and a prefix string to pull a set of data containing the prefix string.

Turns out its relatively easy in mongodb as well.  The only trick is using regular expressions.

For example, I have a collection of accounts.  For each document in this collection, there is a name attribute.  When a user composes a new message, they must select a user to send to.  This combobox can be used to search the accounts collection based on what is typed into the textfield.

Here is how this is achieved on the server side.  The important part is creating a new RegExp object and providing the query string to it:

No comments:

Post a Comment