Skip to content

Instantly share code, notes, and snippets.

@alaz
Created October 13, 2009 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alaz/209412 to your computer and use it in GitHub Desktop.
Save alaz/209412 to your computer and use it in GitHub Desktop.
Simple example for mongo-scala-driver "Getting Started" Wiki page
// 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
@ctataryn
Copy link

Hi, I can't seem to get this example to compile. It gets stuck on line 20 because it cannot find an "of" method. Any ideas?

@ctataryn
Copy link

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

@alaz
Copy link
Author

alaz commented Oct 12, 2010

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