Inserting object's data as a BsonDocument in a MongoDB collection using MongoDB Scala driver.
Add the MongoDB Scala driver reference to build.sbt.
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.
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.
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.
Artwork by:Sam Balye
Browse related articles