如何在 mongodb 中连接 2 个不同的主机

How to connect 2 different hosts in mongodb

我在 ruby 有一个服务,我试图连接两个不同的主机和两个不同的数据库

我正在尝试这样的事情

mongoid.yml

development:
  clients:
    default:
      database: cpeTracking
      hosts:
       - development-shard.mongodb.net:27017
       - development-shard.mongodb.net:27017
       - development-shard.mongodb.net:27017
      options:
        user: my_user
        password: my_password
        auth_source: admin
        ssl: true
      database: testDb
        hosts:
        - localhost:27017

还有我的模特

class Movies
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  store_in database: "testDb"

  field :name, type: String
  field :year, type: Integer
  field :director, type: String
end

当我运行服务时,只连接第一台主机。 我也试过这个解决方案 Connecting to two databases Mongoid 但没用

我找到了答案。 首先,我必须在相同的默认级别创建一个新客户端,我用数据库和主机的信息将其命名为 "secondary"。

development:
  clients:
    default:
      database: my_db
      hosts:
        - development-shard.mongodb.net:27017
        - development-shard.mongodb.net:27017
        - development-shard.mongodb.net:27017
      options:
        user: my_user
        password: my_pass
        auth_source: admin
        ssl: true
    secondary:
      database: testDb
      hosts:
       - localhost:27017

其次。在模型中,我必须添加集合、数据库和将使用

的客户端
class Movies
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  store_in collection: "movies", database: "testDb", client: "secondary"

  field :name, type: String
  field :year, type: Integer
  field :director, type: String
end