Created
October 13, 2009 18:10
-
-
Save alaz/209412 to your computer and use it in GitHub Desktop.
Simple example for mongo-scala-driver "Getting Started" Wiki page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Model | |
case class User(val name: String) | |
// Factory object: | |
object User extends AbstractShape[User] { | |
// one scalar field called "name" | |
object name extends Scalar[String]("name", _.name) with Functional[String] | |
// fields list | |
override lazy val * = name :: Nil | |
// How to extract the model instance from a MongoDB native object? | |
override def factory(dbo: DBObject): Option[User] = | |
for {val name(n) <- Some(dbo)} yield new User(n) | |
} | |
// Suppose we have a DBCollection: | |
val dbColl: DBCollection | |
// Let's make it look like it stores User instances: | |
val users = dbColl of User | |
// Insert few users: | |
def createUser(i: Int) = User("User"+i) | |
for {val obj <- Array.fromFunction(createUser)(10) } | |
users << obj | |
// Test emptiness: | |
if (users.isEmpty) ... | |
// Get the first user | |
val first: Option[User] = users.firstOption | |
// Walk though the collection (you are free to use any filter/flatMap/map/etc. | |
for {val u <- users} ... | |
// Get only first 2 | |
for {val u <- User take 2 in users} ... | |
// Skip first 5 and get 2 users | |
for {val u <- User drop 5 take 2 in users} ... | |
// Query by name | |
val user3 = (User where {User.name eq_? "User3"} take 1 in users).firstOption | |
// Query by regexp | |
val endingBy5 = User.name ~ "r5$".r in users |
Yep, mongo-scala-driver does not provide wrapper around original Mongo
, DB
, etc. interfaces from the Java driver, so that you can selectively wrap what you want into Shapes. That's why you have to explicitly say "this DBCollection is of shape Address"
Thanks for sharing!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Got it figured out by adding the following:
import com.osinka.mongodb._
It should probably be mentioned that the example isn't complete, the dbCol needs to be gotten from Mongo first before you can use it (which is probably implied by the "//Suppose we have a DBCollection" comment)
Fully functional example here:
http://mrico.eu/mrico/entry/quick_start_scala_mongodb