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
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.
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 update a single matching document. You can also specify 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 existing document matching the update 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.
Previous: Database and collections / Next: Find documents