Forked from alaz/mongo-scala-driver first example.scala
Created
November 14, 2009 20:07
-
-
Save alexy/234729 to your computer and use it in GitHub Desktop.
This file contains 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment