官术网_书友最值得收藏!

  • Mastering MongoDB 3.x
  • Alex Giamas
  • 269字
  • 2021-08-20 10:10:52

Connecting using Ruby

Ruby was one of the first languages to have support from MongoDB with an official driver. The official mongo-ruby-driver on GitHub is the recommended way to connect to a MongoDB instance.

Installation is as simple as adding it to the Gemfile:

gem 'mongo', '~> 3.4'
You need to install Ruby, then install RVM from https://rvm.io/rvm/install and finally run  gem install bundler for this.

And then in our class we can connect to a database:

require 'mongo'
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'test')

This is the simplest example possible, connecting to a single database instance called test in our localhost. In most use cases we would at least have a replica set to connect to, as in the following snippet:

client_host = ['server1_hostname:server1_ip, server2_hostname:server2_ip']
client_options = {
database: 'YOUR_DATABASE_NAME',
replica_set: 'REPLICA_SET_NAME',
user: 'YOUR_USERNAME',
password: 'YOUR_PASSWORD'
}
client = Mongo::Client.new(client_host, client_options)

The client_host servers are seeding the client driver with servers to attempt to connect to. Once connected, the driver will determine the server that it has to connect to according to the primary/secondary read or write configuration.

The replica_set attribute needs to match the replica set name to be able to connect.

user and password are optional but highly recommended in any MongoDB instance. It's a good practice to enable authentication by default in the mongod.conf file and we will go over this in Chapter 7. Monitoring, Backup, and Security.

Connecting to a sharded cluster is similar to a replica set with the only difference being that, instead of supplying the server host/port, we need to connect to the mongo router, the mongos process.

主站蜘蛛池模板: 林芝县| 延津县| 涿州市| 正镶白旗| 沙田区| 赤壁市| 滁州市| 黄骅市| 洛隆县| 遂昌县| 涟水县| 高平市| 公安县| 航空| 郴州市| 潼关县| 苏尼特左旗| 镇沅| 绥江县| 漾濞| 青龙| 仁化县| 黑水县| 定边县| 福泉市| 酒泉市| 察哈| 梓潼县| 祁连县| 赫章县| 偃师市| 日土县| 德昌县| 大安市| 禄劝| 南城县| 剑河县| 全南县| 宜兰县| 于田县| 那曲县|