1

The example in the node driver shows a simple regular expression used against a number.

collection.find({'a':/[1|2]/})

where collection is

collection.insert([{'a':1}, {'a':2}, {'b':3}]

This fails for me in both the shell and running the example in node.

Here is the example https://github.com/mongodb/node-mongodb-native/blob/1.4/examples/queries.js

I wouldn't expect this to work as regular expressions are for text ... but its in the current examples ... so I figure it must be correct and I'm missing something.. The sample works fine if the values are strings {a : '1'} ... am I missing something or is the sample out of date ...

2 Answers 2

1

You are not missing anything. A $regex operation will only work on strings. Also from the manual

The $regex operator provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. “PCRE.”)

So the highlighted term there is "strings", and that is exactly how things should be.

From the source of this. It is an "odd" example, but should only be treated as an "example". So there is nothing intrinsically "wrong" with the code. It just doesn't return any results. So in that it is arguably still valid. No-one said it was "supposed" to match documents.

If you believe it should be otherwise, feel free to submit a pull request and or a JIRA

Sign up to request clarification or add additional context in comments.

1 Comment

thanks ... its a little more than odd to me as the example crashes trying to use the returned collection length.
0

If you need to use regular expression with numbers, you can do it like this:

collection.find({ $where: "/[1|2]/.test(this.a)" })

But keep in mind that, according to the documentation, MongoDB can't use indexes with $where:

$where evaluates JavaScript and cannot take advantage of indexes. Therefore, query performance improves when you express your query using the standard MongoDB operators (e.g., $gt, $in).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.