Checking if a field contains a string

johnny picture johnny · May 16, 2012 · Viewed 448.1k times · Source

I'm looking for an operator, which allows me to check, if the value of a field contains a certain string.

Something like:

db.users.findOne({$contains:{"username":"son"}})

Is that possible?

Answer

Parvin Gasimzade picture Parvin Gasimzade · May 16, 2012

You can do it with the following code.

db.users.findOne({"username" : {$regex : ".*son.*"}});