MongoDB: RDBMS style queries Although many document stores (and NoSQL implementations in general) eschew the notion of SQL and thus implement custom query languages and data access schemes, Mongo's query language is SQL-like. In fact, at a high level, it operates a lot like SQL and is rather easy to pick up.
For instance, using Mongo's shell, inserting a document representing a business card is done as follows:
In this case, I've inserted a JSON document into a collection named business_cards by issuing an insert command on that collection directly. I can search the business_card collection via the find command like so:
This would return the document I just inserted. Plus, that document would contain Mongo's _id field, which was automatically generated upon insert. Note that Mongo's query language is closely analogous to SQL -- the same query in SQL would be something like:
Mongo's query language supports a wide variety of searches, ranging from boolean expressions:
This leverages a boolean OR and returns:
It also covers regular expressions:
In return, you get two documents:
Naturally, Mongo supports updating documents and removing them. Updates are quite powerful, as there are a number of operations available for updating various aspects of a document. For instance, updating the cell number in a document containing the Twitter handle "msmith" would be performed as follows:
In this case, the $set modifier changes a particular value in the first document matching the query. If all documents matching a query should be updated, additional parameters to the update command can be added.
Removing documents is similarly straightforward. Simply use the remove command and issue a query:
Finally, Mongo offers MapReduce, a powerful searching algorithm for batch processing and aggregations that is somewhat similar to SQL's group by. At a high level, the MapReduce algorithm breaks a big task into two smaller steps. The map function is designed to take a large input and divide it into smaller pieces, then hand that data off to a reduce function, which distills the individual answers from the map function into one final output. For instance, MapReduce could be used in the business_card collection to determine how many documents contain a Twitter attribute.