7

Does MongoDB supports comparing two fields in same collection by using native operators (not $where and JavaScript)? I already looked at similar questions and all answers used $where / JavaScript.

MongoDB documentation clearly states that:

JavaScript executes more slowly than the native operators listed on this page, but is very flexible.

My primary concern is speed and I would like to use indexes if possible. So is comparing two fields in MongoDB possible without using JavaScript?

Community
  • 1
  • 1
Christian P
  • 12,032
  • 6
  • 60
  • 71
  • Are you absolutely sure that the $where operator is too slow for your use case? – maerics Jan 12 '12 at 14:17
  • @maerics Short answer - yes. If everything else fails $where will be my last resort. But I would very much like to avoid $where and to search by indexed fields if possible. – Christian P Jan 12 '12 at 14:23

2 Answers2

5

This is not currently possible, but it will be possible through the new aggregation framework currently under development (2.1+). This aggregation framework is native and does not rely on relatively slow JavaScript execution paths.

For more details check http://www.mongodb.org/display/DOCS/Aggregation+Framework and the progress at https://jira.mongodb.org/browse/SERVER-447

Remon van Vliet
  • 18,365
  • 3
  • 52
  • 57
2

From reading the documentation you link it doesn't look like MongoDB has the ability to compare two document properties using only native operators.

Perhaps you can modify the documents themselves (and/or the code which saves the documents) to include a boolean property with value resulting from the comparison (ahead-of-time) and then simply query on that new property as needed. You could even index it for even better performance.

maerics
  • 151,642
  • 46
  • 269
  • 291