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
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.
Update a document
Updates are done with the
update operation, 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
arrayFilters criteria can also be specified on update.
Delete a document
.delete function returns a
DeleteBuilder, which allows to perform simple or bulk delete.
.remove operation is now deprecated.
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.
As when using
arrayFilters criteria can be specified for a
.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