Overview
In this guide, you can learn how to interact with MongoDB databases and collections by using the Scala driver.
MongoDB organizes data into a hierarchy of the following levels:
Databases: Top-level data structures in a MongoDB deployment that store collections.
Collections: Groups of MongoDB documents. They are analogous to tables in relational databases.
Documents: Units that store literal data such as string, numbers, dates, and other embedded documents. For more information about document field types and structure, see the Documents guide in the MongoDB Server manual.
Access a Database
Access a database by calling the getDatabase() method on a MongoClient instance.
The following example accesses a database named "test_database":
val database = mongoClient.getDatabase("test_database")
Access a Collection
Access a collection by calling the getCollection() method on a MongoDatabase instance.
The following example accesses a collection named "test_collection":
val collection = database.getCollection("test_collection")
Tip
If the provided collection name does not already exist in the database, MongoDB implicitly creates the collection when you first insert data into it.
Create a Collection
Use the createCollection() method on a MongoDatabase instance to explicitly create a collection in a database.
The following example creates a collection named "example_collection":
val createObservable = database.createCollection("example_collection") Await.result(createObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
You can specify collection options, such as maximum size and document validation rules, by passing a CreateCollectionOptions instance to the createCollection() method. For a full list of optional parameters, see the create command documentation in the MongoDB Server manual.
Get a List of Collections
You can query for a list of collections in a database by calling the listCollections() method of a MongoDatabase instance.
The following example lists all collections in a database:
val results = Await.result(database.listCollections().toFuture(), Duration(10, TimeUnit.SECONDS)) results.foreach(println)
Iterable((name,BsonString{value='test_collection'}), (type,BsonString{value='collection'}), ... ) Iterable((name,BsonString{value='example_collection'}), (type,BsonString{value='collection'}), ... )
To query for only the names of the collections in the database, call the listCollectionNames() method as follows:
val results = Await.result(database.listCollectionNames().toFuture(), Duration(10, TimeUnit.SECONDS)) results.foreach(println)
test_collection example_collection
Tip
For more information about iterating over a Future instance, see Use Futures to Retrieve All Results in the Access Data From an Observable guide.
Delete a Collection
You can delete a collection by calling the drop() method on a MongoCollection instance.
The following example deletes the test_collection collection:
val deleteObservable = database.getCollection("test_collection").drop() Await.result(deleteObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
Warning
Dropping a Collection Deletes All Data in the Collection
Dropping a collection from your database permanently deletes all documents and all indexes within that collection.
Drop a collection only if the data in it is no longer needed.
Delete a Database
You can delete a database by calling the drop() method on a MongoDatabase instance.
The following example deletes the test_database database:
var database = mongoClient.getDatabase("test_database") val deleteObservable = database.drop() Await.result(deleteObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
Warning
Dropping a Database Deletes All Data in the Database
Dropping a database permanently deletes all collections, documents, and indexes within that database.
Drop a database only if you no longer need its data.
Configure Read and Write Operations
You can control how the driver routes read operations by setting a read preference. You can also control options for how the driver waits for acknowledgment of read and write operations on a replica set by setting a read concern and a write concern.
By default, databases inherit these settings from the MongoClient instance, and collections inherit them from the database. However, you can change these settings on your database by using the withReadPreference() method.
The following example accesses a database while specifying the read preference of the database as secondary:
val databaseWithReadPrefs = mongoClient.getDatabase("test_database").withReadPreference(ReadPreference.secondary())
You can also change the read and write settings on your collections by using the withReadPreference() method. The following example shows how to access a collection while specifying the read preference of the collection as secondary:
val collectionWithReadPrefs = database.getCollection("test_collection").withReadPreference(ReadPreference.secondary())
Tip
To see the types of available read preferences, see the API documentation.
To learn more about the read and write settings, see the following guides in the MongoDB Server manual:
Tag Sets
In the MongoDB Server, you can apply key-value tags to replica-set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.
By default, the Scala driver ignores tags when choosing a member to read from. To instruct the Scala driver to prefer certain tags, pass a TagSet instance to the ReadPreference constructor, then pass the ReadPreference instance to the MongoClientSettings you use to instantiate a MongoClient.
In the following code example, the tag set passed to the ReadPreference constructor instructs the Scala driver to prefer reads from the New York data center ('dc': 'ny') and to fall back to the San Francisco data center ('dc': 'sf'):
val tag1 = new Tag("dc", "ny") val tag2 = new Tag("dc", "sf") val tagSet = new TagSet(List(tag1, tag2).asJava) val connectionString = ConnectionString("<connection string URI>") val readPreference = ReadPreference.primaryPreferred(tagSet) val mongoClientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .readPreference(readPreference) .build() val clientWithTags = MongoClient(mongoClientSettings)
Local Threshold
When connecting to a replica set with a non-primary read preference, the driver reads from the nearest eligible replica set member within the latency window. When connecting to a sharded cluster, the driver selects from all reachable mongos instances within the latency window. To learn about read preference modes, see Read
Preference.
By default, the driver uses only those servers whose ping times are within 15 milliseconds of the nearest eligible server.
For example, suppose your replica set has five members and the nearest member has a ping time of 5 milliseconds. With the default localThresholdMS of 15 milliseconds, only members with a ping time of 20 milliseconds or less are within the latency window, as shown in the following table:
Host | Type | Ping Time | Within Latency Window |
|---|---|---|---|
| Primary | 5ms | Yes |
| Secondary | 9ms | Yes |
| Secondary | 13ms | Yes |
| Secondary | 24ms | No |
| Secondary | 42ms | No |
To adjust the latency window, use the localThreshold() method within the ClusterSettings.Builder block provided by the applyToClusterSettings() method of the MongoClientSettings.Builder class. Alternatively, include the localThresholdMS parameter in your connection string URI.
The following example connects to a MongoDB deployment running on localhost:27017 and specifies a local threshold of 35 milliseconds:
val connectionString = ConnectionString("mongodb://localhost:27017") val mongoClientSettings = MongoClientSettings.builder() .applyConnectionString(connectionString) .applyToClusterSettings(builder => builder.localThreshold(35, TimeUnit.MILLISECONDS)) .build() val client = MongoClient(mongoClientSettings)
In the preceding example, the Scala driver distributes reads between matching members within 35 milliseconds of the closest member's ping time.
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API documentation: