Read Data from MongoDB
On this page
Overview
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.
Sample Application
Sample Application
You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:
Ensure you have the Scala driver installed in your Maven or sbt project.
Copy the following code and paste it into a new
.scala
file.Copy a code example from this page and paste it on the specified lines in the file.
1 import org.mongodb.scala._ 2 import org.mongodb.scala.bson.Document 3 import org.mongodb.scala.model.Filters._ 4 import org.mongodb.scala.model.changestream._ 5 6 object 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 }
Find One
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.
Find Multiple
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.
Count Documents in a Collection
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.
Count Documents Returned from a Query
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.
Estimated Document Count
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.
Retrieve Distinct Values
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.
Monitor Data Changes
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.