I recently wrote an article on how to use MongoDB with Elixir. Since that article was released, changes have been made to the MongoDB Elixir package.

In many ways, these changes make the package more approachable and flexible for developers, but they left my old instructions outdated and incomplete.


Previous versions of the MongoDB driver (< 0.2) required that you build your own MongoPool module somewhere in your project:


defmodule MongoPool do
  use Mongo.Pool, name: __MODULE__, adapter: Mongo.Pool.Poolboy
end

This MongoPool module set up your connection pooling (using Mongo.Pool.Poolboy) and was the main process you would instantiate to establish a connection with your MongoDB database:


{:ok, _} = MongoPool.start_link(database: "test")

Once the connection was established, you could query the database through the connection pool, without specifying the PID if the pool’s process:


MongoPool
|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

However, with version 0.2 of the MongoDB driver, things have changed.

Now, you instantiate your connection to your MongoDB database by spinning up the Mongo process directly:


{:ok, mongo_pid} = Mongo.start_link(database: "test")

The first argument to Mongo.find/Mongo.insert_one/etc… is now the Mongo process ID:


mongo_pid
|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

Alternatively, you can name your Mongo process to avoid having to pass the mongo_pid around your application:


{:ok, _} = Mongo.start_link(database: "test", name: :mongo)

:mongo
|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

Out of the box, this will establish a single connection to the database. To enable connection pooling, like we had with our old MongoPool, we need to specify how we want our pooling handled when we spin up our Mongo process:


{:ok, _} = Mongo.start_link(database: "test", name: :mongo, pool: DBConnection.Poolboy)

You then need to specify the pool module you’re using when running MongoDB operations:


:mongo
|> Mongo.find("collection", %{ "foo" => "bar" }, pool: DBConnection.Poolboy)
|> Enum.to_list

The heart of these changes is that the mongodb driver package is now using the DBConnection package, instead of wrapping Poolboy itself.

See the changelog and the GitHub documentation and the Hex documentation for more details.