How Scala interacts with MongoDB

Reading Time: 2 minutes

As a definition, MongoDB is an open source database that uses a document-oriented data model and a non-structured query language. It is one of the most powerful NoSQL systems and databases around today. Being a NoSQL tool means it does not use the usual rows and columns that we so much associated with the relational database management. It is an architecture that is built on collections and documents. The basic unit of data in this database consists of a set of key-value pairs.

The advantages of using documents are:

1)Documents (i.e. objects) correspond to native data types in many programming languages.

2)Embedded documents and arrays reduce the need for expensive joins.

3)Dynamic schema supports fluent polymorphism.

Key Feature of MongoDB are

1)High Performance

2)Rich Query Language

3)High Availability

4)Horizontal Scalability

Here in this Blog, we are going to discuss on MongoDB Scala Driver. The official MongoDB Scala Driver, providing asynchronous event-based observable sequences for MongoDB.

First, we need to add SBT dependencies as,

libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "2.6.0"

You can also download the jars directly from sonatype

After successfully adding dependencies we need to create a connection with MongoDB  Database as

import org.mongodb.scala._

val mongoClient: MongoClient = MongoClient("mongodb://localhost:27017/")
val database: MongoDatabase = mongoClient.getDatabase("mydb")

The MongoClient instance actually represents a pool of connections for a given MongoDB server deployment; you will only need one instance of class MongoClient even with multiple concurrently executing asynchronous operations

And to get a collection into which we want to perform operation on we  use

val collection: MongoCollection[Document] =database.getCollection("test");

Once you are ready with your collection object we can perform operations like insert, delete, update, find etc.

val doc: Document = Document("_id" -> 0, "name" -> "MongoDB", "type" -> "database","count" -> 1, "info" -> Document("x" -> 203, "y"-> 102))
collection.insertOne(doc).results();//Using the results() implicit we block until the observer is completed

Or if we want to add multiple documents together we can do that as well

val documents = (1 to 100) map { i: Int => Document("i" -> i) }

After inserting Documents in MongoDB we can get the count of total Document in Collection by using count() method

val insertAndCount = for {
  countResult <- collection.countDocuments()
} yield countResult
println(s"total # of documents after inserting 100 small ones (should be 101):  ${insertAndCount.headResult()}") 

Where headResult Blocks until the first result of the Observable can be returned

You can  find  all documents in the collection.


Using the printHeadResult() implicit we block until the observer is completed and then print the first result

Get A Single Document with a Query Filter by

import org.mongodb.scala.model.Filters._

collection.find(equal("i", 71)).first().printHeadResult()

The Filter class provides static factory methods for all the MongoDB query operators. Each method returns an instance of the BSON type, which can, in turn, be passed to any method that expects a query filter. We can use a filter for comparison, logically,Arrays,Evaluation,BitwiseGeospatial, Elemets and so

To update at most a single document (maybe 0 if none match the filter), use the updateOne method to specify the filter and the update document.

import org.mongodb.scala.model.Updates._
collection.updateOne(equal("i", 10), set("i", 110)).printHeadResult("Update Result: ")

To delete at most a single document (may be 0 if none match the filter) use the deleteOne method

collection.deleteOne(equal("i", 110)).printHeadResult("Delete Result: ")

Thanks for Reading!!