16.5. Searching a MongoDB Collection
Problem
You want to find objects in your MongoDB collection using Scala and the Casbah driver.
Solution
Use the find
* methods of the
MongoCollection
class to get the
elements you want, specifically the find
and findOne
methods.
Assuming that you have everything set up as shown in Recipe 16.3, the following code demonstrates these techniques:
How to find all the documents in a collection
How to find one document that matches your search criteria
How to find all documents that match your search criteria
How to limit the number of results returned by a
find
query
Here’s the code:
import
com.mongodb.casbah.Imports._
object
Find
extends
App
{
val
collection
=
MongoFactory
.
collection
// (1) find all stocks with find()
// -------------------------------
println
(
"\n___ all stocks ___"
)
var
stocks
=
collection
.
find
stocks
.
foreach
(
println
)
// (2) search for an individual stock
// ----------------------------------
println
(
"\n___ .findOne(query) ___"
)
val
query
=
MongoDBObject
(
"symbol"
->
"GOOG"
)
val
result
=
collection
.
findOne
(
query
)
// Some
val
stock
=
convertDbObjectToStock
(
result
.
get
)
// convert it to a Stock
println
(
stock
)
// (3) find all stocks that meet a search criteria
// -----------------------------------------------
println
(
"\n___ price $gt 500 ___"
)
stocks
=
collection
.
find
(
"price"
$gt
500
)
stocks
.
foreach
(
println
)
// (4) find all stocks that match a search pattern
// -----------------------------------------------
println
(
"\n___ stocks that begin with ...
Get Scala Cookbook 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.