Java Reference
In-Depth Information
Figure 8.5. A portion of the vampire movies database, using the MonjaDB plugin for Eclipse
8.5.2. Querying and mapping MongoDB data
Now that the data is in the database I need to be able to search it and examine the results.
This can be done in a trivial fashion, using the
find
method, or the data can be mapped to
Groovy objects for later processing.
The
find
method on the collection returns all JSON objects satisfying a particular condi-
tion. If all I want is to see how many elements are in the collection, the following suffices:
println db.vampireMovies.find().count()
With no arguments, the
find
method returns the entire collection. The
count
method
then returns the total number.
Mapping JSON to Groovy brings home the difference between a strongly typed language,
like Groovy, and a weakly typed language, like JSON. The JSON data shown is a mix of
strings, dates, integers, and enumerated values, but the JSON object has no embedded type
information. Mapping this to a set of Groovy objects takes some work.
For example, the following listing shows a
Movie
class that holds the data in the JSON
object.
Listing 8.16.
Movie.groovy
, which wraps the JSON data
@ToString(includeNames=true)
class Movie {