首页 > 解决方案 > 在 Elixir 中启动 2 个 MongoDB 连接

问题描述

我正在制作一个需要同时连接到 2 个 mongo 数据库的应用程序。

我正在使用 mongodb (v0.4) 模块。

现在我的主管看起来像这样:

children=[
    worker(Mongo, [[name: :mongo, database: "transit", seeds: ["localhost:27017"], pool: DBConnection.Pool]])
]
opts= [strategy: :one_for_one, name: HugoEtl.Supervisor]
Supervisor.start_link(children, opts) 

我想同时打开另一个连接以将数据从一个连接泵送到另一个连接。

我怎样才能做到这一点。

标签: mongodbelixirerlang-supervisor

解决方案


可能会阻止一个人天真地并行打开 2 个连接的是与等效模块名称相对应的工作人员的自动 ID。

children=[
    worker(Mongo, [[name: :mongo, database: "transit", seeds: ["localhost:27017"], pool: DBConnection.Pool]]), 
    worker(Mongo, [[name: :mongo_final, database: "final", seeds: ["localhost:27017"], pool: DBConnection.Pool]], id: MongoFinal)
]
opts= [strategy: :one_for_one, name: HugoEtl.Supervisor]
Supervisor.start_link(children, opts) 

这将启动 2 个数据库连接,您可以使用以下命令查询每个连接:

# first connection 
Mongo.find(:mongo,"collection",%{})
# second connection 
Mongo.find(:mongo_final,"collection",%{})

推荐阅读