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
?
db.scores.find({a: {'$gte': 2, '$lte': 4}});
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.
It allows MongoDB code to be embedded in an HTML or XML document without having to mess with entities (<
and >
) or CDATA.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With