Docs Menu
Docs Home
/ / /
Scala

Read Data from MongoDB

On this page

  • Overview
  • Sample Application
  • Find One
  • Find Multiple
  • Count Documents in a Collection
  • Count Documents Returned from a Query
  • Estimated Document Count
  • Retrieve Distinct Values
  • Monitor Data Changes

On this page, you can see copyable code examples that show common Scala driver methods you can use to read data from MongoDB.

Tip

To learn more about any of the methods shown on this page, see the link provided in each section.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string URI>, with the relevant values for your MongoDB deployment.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Ensure you have the Scala driver installed in your Maven or sbt project.

  2. Copy the following code and paste it into a new .scala file.

  3. Copy a code example from this page and paste it on the specified lines in the file.

1import org.mongodb.scala._
2import org.mongodb.scala.bson.Document
3import org.mongodb.scala.model.Filters._
4import org.mongodb.scala.model.changestream._
5
6object SampleReadApp {
7
8 def main(args: Array[String]): Unit = {
9 val mongoClient = MongoClient("<connection string URI>")
10 val database: MongoDatabase = mongoClient.getDatabase("<database name>")
11 val collection: MongoCollection[Document] = database.getCollection("<collection name>")
12
13
14 // Start example code here
15
16 // End example code here
17
18 // Wait for the operations to complete before closing client
19 // Note: This example uses Thread.sleep() for brevity and does not guarantee all
20 // operations will be completed in time
21 Thread.sleep(1000)
22 mongoClient.close()
23 }
24}

The following example retrieves a document that matches the criteria specified by the given filter:

val filter = equal("<field>", "<value>")
collection.find(filter).first().subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the first() method, see the Retrieve Data guide.

The following example retrieves all documents that match the criteria specified by the given filter:

val filter = equal("<field>", "<value>")
collection.find(filter).subscribe((doc: Document) => println(doc.toJson()),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the find() method, see the Retrieve Data guide.

The following example returns the number of documents in the specified collection:

collection.countDocuments()
.subscribe((count: Long) => println(s"Number of documents: $count"),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the countDocuments() method, see the Count Documents guide.

The following example returns the number of documents in the specified collection that match query criteria:

collection.countDocuments(equal("<field>", "<value>"))
.subscribe((count: Long) => println(s"Number of documents: $count"),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the countDocuments() method, see the Count Documents guide.

The following example returns an approximate number of documents in the specified collection based on collection metadata:

collection.estimatedDocumentCount()
.subscribe((count: Long) => println(s"Estimated number of documents: $count"),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the estimatedDocumentCount() method, see the Count Documents guide.

The following example returns all distinct values of the specified field name in a given collection:

collection.distinct("<field>")
.subscribe((value: String) => println(value),
(e: Throwable) => println(s"There was an error: $e"))

To learn more about the distinct() method, see the Retrieve Distinct Field Values guide.

The following example creates a change stream for a given collection and prints out subsequent change events in that collection:

val changeStreamObservable = collection.watch()
changeStreamObservable.subscribe(
(changeEvent: ChangeStreamDocument[Document]) => {
println(s"Received a change to the collection: ${changeEvent}")
},
(e: Throwable) => {
println(s"Encountered an error: ${e.getMessage}")
},
() => println("Completed")
)

To learn more about the watch() method, see the Monitor Data Changes guide.

Back

Time Series