Reading Object Data from MongoDB

Web application needs a way to efficiently store and retrieve object data such as subscribers, users, sessions, keys. At LineDrop, we chose to store our data using MongoDB due to high performance on large datasets and the ease of implementation.

Share:

Library Dependencies

Add the following line 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:

Find Method

Example: LineDrop Play/Scala Web Application - Database Utility

Usage Example

How Find Method Works

The find method searches a collection for a document based on a criteria.

The method accepts the search key, search value, and the collection name.  It opens a client connection to the database server, then accesses the database and the collection.

The method uses the driver’s find method, which is a threaded operation.  Unlike the insert method, the find method returns a value. To wait for the return value, the method utilizes Scala’s Future/Promise structure.

An empty result sequence is initialized.

A promise container is set up.

Driver’s find operation thread is started, looking for a document in the collection that has a search_by key that matches the specified value. The results are sorted by the created timestamp with the most recent document first.

A subscription is registered with the driver’s find operation. Some time in the future, the operation is completed, the sequence of found documents is appended to result_seq and the promise container is set. Scala’s Future/Promise structure enables the method to wait for the thread to complete.

Future variable is initialized.

Future then waits for the promise.

Instead of returning the most recent result, the method returns Scala’s Option[Object] which allows to account for a case that nothing has been found (None) or a document matching the criteria has been found (Some[Document]).


References

Related Articles

Browse related articles