Complex queries

We now know how to convert DBObject instances to custom Scala classes. In this section, you will learn how to construct queries that only return a subset of the documents in the collection.

In the previous section, you learned to retrieve all the documents in a collection as follows:

scala> val objs = collection.find().toList
List[DBObject] = List({ "_id" : { "$oid" : "56365cec46f9534fae8ffd7f"} ,...

The collection.find() method returns an iterator over all the documents in the collection. By calling .toList on this iterator, we materialize it to a list.

We can customize which documents are returned by passing a query document to the .find method. For instance, we can retrieve documents for a specific login name:

scala> val query ...

Get Scala for Data Science 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.