In MongoDB, “$where” is used to specify arbitrary Javascript that allows one to run more specialized queries, especially the boolean “OR” criteria.

Lets continue with the example of our “address” collection that we first discussed under Find. Documents in this collection contain address information, for example:

	"Street":"123 ABC Street",
	"Street2": "Search Boulevard",
	"City": "Allentown",
	"State": "PA",
	"Country": "United States"

Now, if we were to fetch all the address in Allentown and Pittsburgh only, we would specify a JavaScript statement (condition, that evaluates to true or false) as follows:



This same can also be expressed in the form of a JavaScript function:



Please note: You could achieve the same results by specifying your JavaScript inside the “Find” query (see pic below). Also note that if you specify such a condition in both the “Find” popout box, and the “Where” popout box, then the JavaScript in “Where” takes precedence and overwrites those specified under “Find”.


Tags: ,