Reactive Scala Driver for MongoDB
Asynchronous & Non-Blocking
MongoDB offers different kinds of write operations: insertion, update or removal. Using ReactiveMongo Data, this can be performed asynchronously.
Insert a document
Insertions are done with the
Future[LastError] previously returned by the write operations is replaced by
Future[WriteResult] in the new API.
WriteResult is a special document that contains information about the write operation, like the number of documents that were updated.
If the write result actually indicates an error, the
Future will be in a
failed state (no need to check for
Like all the other collection operations (in
GenericCollection trait), you can insert any writeable value to
insert(). With the default BSON serialization, that means provided there a
BSONDocumentWriter for its type in the implicit scope. So, considering the
Person case class:
When calling a write operation, it’s possible to handle some specific error case by testing the result, using some pattern matching utilities.
Insert multiple document
bulkInsert makes it possible to insert multiple documents.
Update a document
Updates are done with the
update() method, which follows the same logic as
By default, the update operation only updates a single matching document. You can also indicate that the update should be applied to all the documents that are matching, with the
It’s possible to automatically insert data if there is no matching document using the
Remove a document
By default, this
remove function deletes all the documents that match the
selector. You can change this behaviour by setting the
firstMatchOnly parameter to
ReactiveMongo can even store instances of a custom class directly by defining a custom writer.
Find and modify
ReactiveMongo also supports the MongoDB
In the case you want to update the age of a document in a collection of persons, and at the same time to return the information about the person before this change, it can be done using
As on a simple update, it’s possible to insert a new document when one does not already exist.
findAndModify approach can be used on removal.
.db has been deprecated as it didn’t offer a sufficient guaranty that it can initially find an active channel in the connection pool (
.database resolution must be used (see connection tutorial).
If the deprecated database resolution is still used, a runtime error such as
ConnectionNotInitialized can be raised when writing documents.
Previous: Database and collections / Next: Find documents