MongoDB Regex Search on Integer Value

Gary Richardson picture Gary Richardson · May 25, 2010 · Viewed 31.5k times · Source

I want to regex search an integer value in MongoDB. Is this possible?

I'm building a CRUD type interface that allows * for wildcards on the various fields. I'm trying to keep the UI consistent for a few fields that are integers.

Consider:

> db.seDemo.insert({ "example" : 1234 });
> db.seDemo.find({ "example" : 1234 });
{ "_id" : ObjectId("4bfc2bfea2004adae015220a"), "example" : 1234 }
> db.seDemo.find({ "example" : /^123.*/ });
> 

As you can see, I insert an object and I'm able to find it by the value. If I try a simple regex, I can't actually find the object.

Thanks!

Answer

dalton picture dalton · May 25, 2010

If you are wanting to do a pattern match on numbers, the way to do it in mongo is use the $where expression and pass in a pattern match.

> db.test.find({ $where: "/^123.*/.test(this.example)" })
{ "_id" : ObjectId("4bfc3187fec861325f34b132"), "example" : 1234 }