Creating a Map of Objects from MongoDB Collection

Learn to read a MongoDB collection and create a Scala object from each document using Play Framework.

Share:

Library Dependencies

Add MongoDB Scala driver library dependencies to build.sbt.

Configuration

Storing database connection parameters in the application configuration file helps to avoid “hard-coding” the variables and makes it easy to change the server location as well as the name of the database. Add the following entry to conf/application.conf and update the database name:

Server key points to where the database engine is running. In this case, the database is running on the same machine as the application.

Database key is the name of the database to be created and used by the application. In this case, the database is named sample.

Find_all Method

Usage Example

How Find_all Method Works

The method uses the driver's find operation to read the entire collection. Once the find operation is completed, a subscription event is fired and the document sequence is appended tot the returning sequence.

Scala's Promise/Future device is used to wait for the operation to complete.

Sample Code

LineDrop Play/Scala Web Application - Database Utility


References

Related Articles

Browse related articles