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 = DBObject("login" -> "mojombo") query: DBObject = { "login" : "mojombo"} scala> val objs = collection.find(query).toList List[DBObject] = List({ "_id" : { "$oid" : "562e922546f953739c43df02"} , "login" : "mojombo",...
MongoDB queries...