1

How do you put a variable inside this expression? I tried

var myVariable = 'something';

db.test.find({$where: "myVariable.match( ... )"});

but I get an error "myVariable is not defined". What's the way to do this?

16
  • I tried what you have just posted. Didn't get any error. Can you elaborate more? Commented Apr 20, 2015 at 5:45
  • If you want to do this you will need to use $eval to put the variable in the scope of the function Commented Apr 20, 2015 at 7:41
  • 1
    Note: use of $where is generally discouraged as JavaScript evaluation cannot take advantage of indexes. If you can include an example of a sample document and actual query you're trying to construct, there is likely a more performant alternative to recommend. Commented Apr 20, 2015 at 8:34
  • @stennie I'm not sure there is. {$where: "myVariable.match(new RegExp(this.test + '$'))"}. If myVariable = 'something', it should get documents that match the end substring, e.g., mething, thing, ing. Commented Apr 20, 2015 at 8:58
  • you can use $regex Commented Apr 20, 2015 at 9:02

1 Answer 1

2

You need your variable to be in the local scoop of $where like this:

db.test.find({ "$where": function(){
    var myVariable = "something";
    return myVariable.match( ... )
    }
);
Sign up to request clarification or add additional context in comments.

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.