Introduction to MongoDB Query Language

MongoDB queries are represented as a JSON-like structure, just like documents. To build a query, you specify a document with properties you wish the results to match. MongoDB treats each property as having an implicit boolean AND. It natively supports boolean OR queries, but you must use a special operator ($or) to achieve it. In addition to exact matches, MongoDB has operators for greater than, less than, etc.

Sample query document to match all documents in the users collection with firstname “jane”:

q  = {
    "firstname" : "jane"
}

If we wanted to retrieve all documents with firstname “jane” AND surname “doe”, we would write:

q = {
    "firstname" : "jane",
    "surname" : "doe"
}

If we wanted to retrieve all documents with a score value of greater than 0, we would write:

q = {
    "score" : { "$gt" : 0 }
}

Notice the use of the special “$gt” operator. The MongoDB query language provides a number of such operators, enabling you to build quite complex queries.

See the section on MongoDB Query Operators for details.

Get MongoDB and Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.