Skip to content
GeoffreyLong edited this page Jun 27, 2014 · 3 revisions

The query language for Warmongo is identical to pymongo, and therefore follows the standard query language for MongoDB. There is extensive documentation for this on MongoDB's website, for details you can look there.

Finding Many

To find many elements, use find():

countries = Country.find()

find() returns a generator which iterates across the set of results.

Validation Exceptions

When iterating over a result set, if a document from the database fails validation, a ValidationError will be thrown. In the case where you have an external process that may put invalid data into your database (or the schema has changed) you may need to use manual generator iteration:

result = Country.find()

while True:
    try:
        country = result.next()

        # Do stuff with the current document
    except warmongo.exceptions.ValidationError
        # An element had invalid data - at the moment this unfortunately only
        # prints the validation error, it does not give information about the
        # object that failed.
        print "Invalid data in the database: %s" % traceback.format_exc()
    except StopIteration:
        # We're done looping over the result set
        break

Sorting

To sort, pass in a sort keyword argument:

# Sort ascending by name
result = Country.find(sort=[("name", 1)])

# Sort ascending by continent (ascending) and population (descending)
result = Country.find(sort=[("continent", 1), ("population": -1)])

You can also use warmongo.ASCENDING or warmongo.DESCENDING instead of 1 and -1 if you prefer.

Skip/Limit

Skip and limit are implemented as keyword arguments:

result = Country.find(limit=10, skip=5)

Fields

You can specify which fields you want to include/exclude. This follows pymongo's format:

result = Country.find(fields=["name"])

result = Country.find(fields={"name": -1})

Batching

By default MongoDB has a cursor timeout of 10 minutes. If your iteration over a result set takes longer than that, you will get an exception and will have to redo the query.

Fortunately, find() accepts a batch_size option that will run multiple queries without you having to worry about it:

big_result = AllTheThings.find(batch_size=1000)

for result in big_result:
    # Do something with the document

A downside of batch_size is that you cannot use it with limit or skip at the moment. This may change in a future version of Warmongo.

Clone this wiki locally