Mongo regex query with single quote?

1,787 views
Skip to first unread message

rl

unread,
Apr 24, 2012, 10:17:09 AM4/24/12
to mongod...@googlegroups.com
How do I do a regex query for a string that contains a single quote?

e.g.

Using a forward slash doesn't escape the quote:

db.mydb.find({lastname:/O\'Reilly/})      

How do I escape it?

Thanks in advance.

Виталий Ф.

unread,
Apr 24, 2012, 10:19:06 AM4/24/12
to mongod...@googlegroups.com
[']
db.mydb.find({lastname:/O[']Reilly/})     

2012/4/24 rl <rob...@cloud2market.com>

--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mongodb-user/-/8J7QBIVjXXMJ.
To post to this group, send email to mongod...@googlegroups.com.
To unsubscribe from this group, send email to mongodb-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mongodb-user?hl=en.



--
Фунтиков Виталий Викторович
веб-разработчик

rl

unread,
Apr 24, 2012, 10:38:45 AM4/24/12
to mongod...@googlegroups.com
That didn't work.

> db.mydb.find({lastname:/O[']Reilly/})  
... 
... 

Sam Millman

unread,
Apr 24, 2012, 10:57:59 AM4/24/12
to mongod...@googlegroups.com
Try using a JS regex object instead.

Inline regex like that has its limitations.

--
You received this message because you are subscribed to the Google Groups "mongodb-user" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mongodb-user/-/JF_gYm893WMJ.

Marc

unread,
Apr 24, 2012, 11:44:04 AM4/24/12
to mongodb-user
There are several ways to do this. The following should all work:

> db.test.save({_id:1, name:"O'Reilly"})
> db.test.find({name:{$regex:"O'Reilly"}})
{ "_id" : 1, "name" : "O'Reilly" }
> db.test.find({name:{$regex:"O\'Reilly"}})
{ "_id" : 1, "name" : "O'Reilly" }

You can also use the hexadecimal value for the character.

> db.test.find({name:{$regex:"O\x27Reilly"}})
{ "_id" : 1, "name" : "O'Reilly" }
> db.test.find({name:/O\x27Reilly/})
{ "_id" : 1, "name" : "O'Reilly" }
>

There is more information on Regular Expressions on the Advanced
Queries page:
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-RegularExpressions
Reply all
Reply to author
Forward
0 new messages