4

So, been working on a smaller project with Play, ReactiveMongo and MongoDB. My question is about the application.conf part for ReactiveMongo, have the standard googlable one:

mongodb = {
  db = "db1"
  servers = [ "localhost:27017" ]
  credentials = {
    username = "auser"
    password = "apassword"
  }
}

And to access a collection, in Scala:

def sessionCollection: JSONCollection = db.collection[JSONCollection]("session")

So, since MongoDB locks at database level for writes, I'm looking for a solution to use several databases.

Question is: how do I configure multiple databases so I can define collections like above, from those databases?

MongoDB 2.6.x, Play 2.3.x, Reactivemongo 0.10.5.0.akka23

Edit: I should say that I already know about this, doing it manually with code, but I wanted to know if there were any Play specific known solution I've failed to reach via Google.

cchantep
  • 9,118
  • 3
  • 30
  • 41
Wrench
  • 4,070
  • 4
  • 34
  • 46
  • 1
    As indicated in the [documentation](http://reactivemongo.org/releases/0.12/documentation/tutorial/play.html), since 0.12.0 "you can use ReactiveMongo with multiple connection pools (possibly with different replica sets and/or different options), using the @NamedDatabase annotation" – cchantep Dec 30 '16 at 16:07
  • Thank you for that input, @cchantep. Can you please write that as an answer and I will accept it. – Wrench Jan 03 '17 at 10:59

1 Answers1

1

In your Play application, you can use ReactiveMongo with multiple connection pools (possibly with different replica sets and/or different options), using the @NamedDatabase annotation.

Consider the following configuration, with several connection URIs.

# The default URI
mongodb.uri = "mongodb://someuser:somepasswd@localhost:27017/foo"

# Another one, named with 'bar'
mongodb.bar.uri = "mongodb://someuser:somepasswd@localhost:27017/lorem"

Then the dependency injection can select the API instances using the names.

import javax.inject.Inject

import play.modules.reactivemongo._

class MyComponent @Inject() (
  val defaultApi: ReactiveMongoApi, // corresponds to 'mongodb.uri'
  @NamedDatabase("bar") val barApi: ReactiveMongoApi // 'mongodb.bar'
) {

}
cchantep
  • 9,118
  • 3
  • 30
  • 41