Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do MongoDB queries use $gt and $lte instead of > and <=?

I'm new to MongoDB. It seems to be built on the JavaScript syntax. Why can't it use clearer comparison operators like < and >= instead of $gt and $lte?

Example from online shell:

db.scores.find({a: {'$gte': 2, '$lte': 4}});

like image 490
Petrus Theron Avatar asked Dec 28 '10 09:12

Petrus Theron


2 Answers

My guess is that they felt that too often you would forget the quotes and write {a: {>: 2}}. In JavaScript, and some other languages, it's perfectly ok to leave out the quotes when writing $gte (e.g. {a: {$gte: 2, $lte: 4}} works, as does {"a": {"$gte": 2, "$lte": 4}}. This saves a lot of typing when you're trying out queries in the Mongo shell.

I'm not sure if you're asking about this, but let me tackle the question why the query language doesn't look more like SQL, e.g. why can't we write the query as a >= 2 && a <= 4 (aside from in $where queries). The reason for this is that the only way to run that query is to parse the JavaScript and run in for each document. It would be impossible to use indices, and every document would have to be converted from the BSON data stored on disk to a JavaScript object in memory (and by the way, this is what happens when you do a $where query, a group or a map reduce).

The elegance of using JSON/BSON notation for queries is that they are pure data and can be manipulated and analyzed -- both on the client and server sides. On the server the query is never passed through a JavaScript interpreter, rather it is fed to a query planner that picks it apart, formulates a plan and executes it. On the client the query can be built using the client language's own datastructures and converted into a universal representation (i.e. BSON) only when passed to the server.

like image 178
Theo Avatar answered Oct 09 '22 18:10

Theo


It allows MongoDB code to be embedded in an HTML or XML document without having to mess with entities (&lt; and &gt;) or CDATA.

like image 45
dan04 Avatar answered Oct 09 '22 19:10

dan04