Posted on by & filed under Content - Highlights and Reviews, Programming & Development, Web Development.

MongoDB is a NoSQL document-oriented database that enables applications to readily scale with increased load. In a previous article, we covered MongoDB’s basics and explained how data can be modeled in it as well as the programming environment it supports. In this article, we will cover one particular feature of Mongo, namely its document-based querying language, which is MongoDB’s counterpart to Structured Query Language (SQL) in relational databases.

Basics of querying in MongoDB

In Mongo, the querying is supported using a document-based query language. Just like Mongo documents, this query language is essentially a JSON document that has fields that specify the values to be searched. This query document is passed as a parameter to the various methods that require documents to be filtered such as find and update. For example, to find all of the users that have the last name ‘Smith’, we can search the “users” collection as follows:

Similarly, to search for users whose age is more than 25, we can use the following query:

Here the element ‘$gt’ has a special interpretation as it stands for ‘greater than’. This query will thus return the desired result. The query language is composed of such special elements that are interpreted by MongoDB to perform the specified search operation. Next, we will cover some of the common ones.

Filtering

The most common querying operations involve filtering data based on some criteria. Mongo provides a rich set of options to filter documents.

As illustrated previously, to search for a field containing specific data you can simply use that value as the search criteria. For example:

This query will return all users with the last_name field equal to Smith. To search for users not having the last name ‘Smith’, we can use:

Here the element “$ne” is used to specify not equal to ‘Smith’. Similarly to search based on conditionals such as greater to (>), greater or equal to (>=), less than (<), less than or equal to (<=), Mongo provides the operators $gt, $gte, $lt and $lte, respectively. For example:

Selection

The process of including or excluding certain fields from the result set is called a selection. In MongoDB, selection criteria takes the form of a document as well (just like query documents) that specifies which fields should be included and/or excluded.

To include a field in the document, specify its value as ‘1’ in the selection document:

This will return all documents in the users collection (since the query parameter is empty) and only show the “age” field in the returned documents (as well as the special “_id” field).

To exclude a field in the returned document, specify its value as ‘0’:

Note that the inclusion or exclusion of fields cannot be mixed together in a single selection document.

Sorting

The documents returned by the find method can be readily searched by applying the sort method:

This query will search for users with age greater than zero and sort them in ascending order of their last names. The sort method is really a shortcut provided by the Mongo shell. Another method for specifying the sort order is by using two special operators “$query” and $orderby”. The $query operator is simply assigned the query document for filtering results, whereas the $orderby document specifies the sorting order of the documents. For example, the above query can be rewritten as:

If the sort order has to be in descending order, use a negative value.

Conclusion

In this article we covered the basics of MongoDB’s query language. There is a whole lot more to the rich querying facilities offered by Mongo. For more in depth coverage, navigate to http://www.mongodb.org/display/DOCS/Querying.

Safari Books Online has the content you need

Below are some MongoDB books to help you develop applications, or you can check out all of the MongoDB books and training videos available from Safari Books Online. You can browse the content in preview mode or you can gain access to more information with a free trial or subscription to Safari Books Online.

MongoDB in Action is a comprehensive guide to MongoDB for application developers. The book begins by explaining what makes MongoDB unique and describing its ideal use cases. A series of tutorials designed for MongoDB mastery then leads into detailed examples for leveraging MongoDB in e-commerce, social networking, analytics, and other common applications.
MongoDB and Python is a cookbook-style text to help Python programmers work with MongoDB. It is full of useful, practical recipes for solving real-world problems ranging from how to do fast geo queries for location-based apps to efficiently indexing your user documents for social-graph lookups to how best to integrate MongoDB with the Pyramid Web framework.
Learn how to create large MongoDB clusters! Scaling MongoDB shows you how to use MongoDB efficiently for very large databases. It Covers sharding, cluster setup, and administration.

About the authors

Salman Ul Haq is a techpreneur, co-founder and CEO of TunaCode, Inc., a startup that delivers GPU-accelerated computing solutions to time-critical application domains. He holds a degree is Computer Systems Engineering. His current focus is on delivering the right solution for cloud security. He can be reached at salman@tunacode.com.
Shaneeb Kamran is a Computer Engineer from one of the leading universities of Pakistan. His programming journey started at the age of 12 and ever since he has dabbled himself in every new and shiny software technology he could get his hands on. He is currently involved in a startup that is working on cloud computing products.

Tags: JSON, MongoDB, Query, SQL,

Comments are closed.