views:

254

answers:

2

I'm using mongodb 1.4.

I want query something as SQL's like.

For an example in SQL:

select * from users where name like '%m%'

How to do the same in mongodb? I can't find a operator for like in the document of http://www.mongodb.org/display/DOCS/Advanced+Queries

+2  A: 

You would use regex for that in mongo.

e.g: db.users.find({"name": /^m/})

jpartogi
+3  A: 

That would have to be:

db.users.find({"name": /.m./})

or, simpler,

db.users.find({"name": /m/})

You're looking for something that contains "m" somewhere (SQL's '%' operator is equivalent to regexps' '.*'), not something that has "m" anchored to the beginning of the string.

Kyle H
@Kyle, is searching by regex expensive?
Freewind
@Freewind: NO it's not expensive.
jpartogi
Actually, it depends. If the query doesn't use an index, and must do a table scan, then it can certainly be expensive. If you're doing a 'starts with' regex query, then that can use an index. Best to run an explain() to see what's happening.
Kyle Banker
When not anchored to the beginning of the string, it is somewhat expensive. But then again, so is a `LIKE` query in SQL.
Emily
@Freewind: Under most circumstances, regexp searching is much more expensive than LIKE, as regular expressions can have more options. However, regular expressions have also been around for decades, and there are many, many implementations that optimize the expensive parts out, most notably the "perl-compatible regular expression" (PCRE) package.I fully endorse @kb's suggestion, the explain, to see what's being queried and its decision tree on how to process it.
Kyle H