Docs Menu
Docs Home
/ / /
Scala

Databases and Collections

On this page

  • Overview
  • Access a Database
  • Access a Collection
  • Create a Collection
  • Get a List of Collections
  • Delete a Collection
  • Configure Read and Write Operations
  • Tag Sets
  • Local Threshold
  • API Documentation

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 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 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.

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.

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.

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.

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())

To learn more about the read and write settings, see the following guides in the MongoDB Server manual:

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)

If multiple replica-set members match the read preference and tag sets you specify, the Scala driver reads from the nearest replica-set members, chosen according to their ping time.

By default, the driver uses only those members whose ping times are within 15 milliseconds of the nearest member for queries. To distribute reads between members with higher latencies, 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.

To learn more about any of the types or methods discussed in this guide, see the following API documentation:

Back

Configure TLS