Docs Menu
Docs Home
/ / /
Scala
/

Quick Start (Case Class Examples)

On this page

  • Overview
  • Configuring Case Classes
  • Insert a Person
  • Insert Multiple Person Instances
  • Querying the Collection
  • Find the First Matching Person
  • Return All Documents
  • Retrieve a Person By Using a Query Filter
  • Find Matching Person Instances
  • Update Documents
  • Delete Documents

This guide is similar to the Quick Start guide but uses case classes to model documents instead of the generic Document class.

The code examples in this guide come from the QuickTourCaseClass.scala file in the driver source code GitHub repository.

Important

See the BSON Macros documentation for information about using macros for configuring case class support with your MongoCollection instance.

First, create the case class you want to use to represent the documents in the collection. The following code creates a Person case class and companion object:

import org.mongodb.scala.bson.ObjectId
object Person {
def apply(firstName: String, lastName: String): Person =
Person(new ObjectId(), firstName, lastName)
}
case class Person(_id: ObjectId, firstName: String, lastName: String)

Note

In the companion object, the apply() method can automatically assign an _id value when creating new instances that don’t include one. In MongoDB the _id field represents the primary key for a document, so by having an _id field in the case class, you allow access to the primary key.

When using Person with a collection, there must be a Codec that can convert it to and from BSON. The org.mongodb.scala.bson.codecs.Macros companion object provides macros that can automatically generate a codec for case classes at compile time. The following example creates a new CodecRegistry that includes a codec for the Person case class:

import org.mongodb.scala.bson.codecs.Macros._
import org.mongodb.scala.MongoClient.DEFAULT_CODEC_REGISTRY
import org.bson.codecs.configuration.CodecRegistries.{fromRegistries, fromProviders}
val codecRegistry = fromRegistries(fromProviders(classOf[Person]), DEFAULT_CODEC_REGISTRY )

Once the CodecRegistry is configured, the next step is to create a MongoCollection[Person]. The following example uses the test collection from the mydb database:

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("mydb").withCodecRegistry(codecRegistry)
val collection: MongoCollection[Person] = database.getCollection("test")

Note

The CodecRegistry can be set when creating a MongoClient, at the database level, or at the collection level. The API is flexible, allowing for different CodecRegistry instances as required.

With the correctly configured MongoCollection, inserting Person instances into the collection is simple:

val person: Person = Person("Ada", "Lovelace")
collection.insertOne(person).results()

To insert multiple Person instances, use the insertMany() method. The following example uses the printResults() implicit and blocks until the observer is completed and then prints each result:

val people: Seq[Person] = Seq(
Person("Charles", "Babbage"),
Person("George", "Boole"),
Person("Gertrude", "Blanch"),
Person("Grace", "Hopper"),
Person("Ida", "Rhodes"),
Person("Jean", "Bartik"),
Person("John", "Backus"),
Person("Lucy", "Sanders"),
Person("Tim", "Berners Lee"),
Person("Zaphod", "Beeblebrox")
)
collection.insertMany(people).printResults()

This code outputs the following message:

The operation completed successfully

Use the find() method to query a collection.

Querying the collection uses the same API used in the Quick Start:

collection.find().first().printHeadResult()

The example prints the first Person in the collection:

Person(58dd0a68218de22333435fa4, Ada, Lovelace)

To retrieve all the documents in the collection, use the find() method. The find() method returns a FindObservable instance that provides a fluent interface for chaining or controlling find operations. The following uses prints all the documents in the collection as Person instances:

collection.find().printResults()

To return a subset of the documents in our collection, pass a filter to the find() method. For example, the following example returns the first Person whose first name is "Ida":

import org.mongodb.scala.model.Filters._
collection.find(equal("firstName", "Ida")).first().printHeadResult()

This example outputs the following result:

Person(58dd0a68218de22333435fa4, Ida, Rhodes)

Tip

You can use the Filters, Sorts, Projections and Updates helpers to enable simple and concise ways of building queries.

The following filter finds all Person instances where the firstName starts with "G", sorted by lastName:

collection.find(regex("firstName", "^G")).sort(ascending("lastName")).printResults()

This example prints out the Person instances for "Gertrude", "George" and "Grace".

There are many update operators supported by MongoDB. Use the Updates helpers to help update documents in a collection.

The following update corrects the hyphenation for "Tim Berners-Lee":

collection.updateOne(equal("lastName", "Berners Lee"), set("lastName", "Berners-Lee"))
.printHeadResult("Update Result: ")

The update methods return an UpdateResult, which provides information about the operation, including the number of documents modified by the update.

To delete at most a single document, or none if no documents match the filter, use the deleteOne() method:

collection.deleteOne(equal("firstName", "Zaphod")).printHeadResult("Delete Result: ")

Back

Quick Start