Storing Object in MongoDB

Inserting object's data as a BsonDocument in a MongoDB collection using MongoDB Scala driver.


Library Dependencies

Add the MongoDB Scala driver reference to build.sbt.

Database Object

Add a utilities package to the app directory. Add an object named Database to the utilities package including the import statements.

Add a new insert method to the Database object.

Usage Example

How Storing Object's Data Works

The insert method inserts a single document into a collection. The method accepts a document and a collection name as parameters. It opens a client connection to the database server, then accesses the database and the collection.

The method uses the driver’s insertOne method which is a threaded operation. An observer is registered with the tread to report back once the insert operation is completed. Critical observer methods are overridden to capture the result.

  • onNext: current document has been successfully inserted
  • onError: an error has occurred
  • onComplete: the thread has finished

Client is explicitly closed when the thread is finished or an error has occurred. We discovered from experience that if the client is not explicitly closed, the connection is kept open too long creating a potential memory leak. The method returns no value. Once it is called, it simply runs its thread to completion.

Code Example

LineDrop Play/Scala Web Application - Database Utility


MongoDB Scala Driver

Artwork by:

unsplash-logoSam Balye

Related Articles

Browse related articles