Aleksandar Vucetic
Aleksandar Vucetic

Reputation: 14953

Mongodb javascript expressions and $where

Are there any performance impacts using javascript expressions inside mongodb query instead standard BSON notation. For example:

>db.myCollection.find( { a : { $gt: 3 } } );
>db.myCollection.find( { $where: "this.a > 3" } );

Will the first query be faster than the second one if there is no index on a column? Also, is there any way to write query

>db.myCollection.find( { $where: "this.a / 10 > 3" } );

or

>db.myCollection.find( { $where: "this.a / this.b > 3" } );

without using $where notation?

Upvotes: 0

Views: 1955

Answers (3)

Gates VP
Gates VP

Reputation: 45297

Will the first query be faster than the second one if there is no index on a column?

In both cases the first on will basically always be faster. The $where clause will use the javascript engine. There can only be one javascript engine running per instance, so it may have to wait. Additionally, the $where clause will have to move objects into and out of the javascript VM which adds overhead and will be slower.

Also, is there any way to write query... .find( { $where: "this.a / this.b > 3" } ); without using $where notation?

The answer here is no. The query engine does not support any query where comparing data within an object. The only workarounds here are to:

  1. Pre-compute the column (which I'm sure you're trying to avoid)
  2. Run a for loop somewhere and do this "manually". This can be done with a Map/Reduce or a client-side query.

Of course, both solutions are sub-optimal. This is definitely a whole in MongoDB's functionality.

Upvotes: 2

mjc
mjc

Reputation: 3426

"Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information."

See the following for more details: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-JavascriptExpressionsand%7B%7B%24where%7D%7D

Upvotes: 0

elijah
elijah

Reputation: 2924

from here:

http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-%7B%7B%24where%7D%7DClausesandFunctionsinQueries

"Note: if a normal data-driven BSON query expression is possible, use that construction. Use $where only when you must it is significantly slower."

For your second question: can you do

{ a : { $gt: 0.3 } }

Upvotes: 2

Related Questions