Connecting to MongoDB
There are two ways to connect to MongoDB. The first is by using the driver for your programming language. The second is by using an ODM layer to map your model objects to MongoDB in a transparent way. In this section, we will cover both ways, using three of the most popular languages for web application development: Ruby, Python, and PHP.
Connecting using Ruby
Ruby was one of the first languages to have support from MongoDB with an official driver. The official MongoDB Ruby driver on GitHub is the recommended way to connect to a MongoDB instance. Perform the following steps to connect MongoDB using Ruby:
- Installation is as simple as adding it to the
Gemfile
, as shown in the following example:gem 'mongo', '~> 2.17'
- Then, in our class, we can connect to a database, as shown in the following example:
require 'mongo' client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'test')
- This is...