Overview
In this guide, you can learn how to use MongoDB databases and collections with Ruby driver.
MongoDB organizes data into a hierarchy of the following levels:
Databases: The top level of data organization in a MongoDB instance.
Collections: MongoDB stores documents in collections. They are analogous to tables in relational databases.
Documents: Contain literal data such as string, numbers, dates, and other embedded documents.
For more information about document field types and structure, see the Documents guide in the MongoDB Server manual.
Access a Database
Access a database by creating a Mongo::Client instance with the desired database name.
The following example accesses a database named test_database:
client = Mongo::Client.new(['127.0.0.1:27017'], database: 'test_database') database = client.database
Access a Collection
Access a collection by using the [] method on an instance of your database.
The following example accesses a collection named test_collection:
database = client.database collection = database['test_collection']
Tip
If the provided collection name does not already exist in the database, MongoDB implicitly creates the collection when you first insert data into it.
Create a Collection
While the Ruby driver for MongoDB does not have a direct create_collection method, you can use the create method to create a collection with specific options.
The following example creates a collection called example_collection with specific options:
database = client.database database[:example_collection].create(capped: true, size: 1024)
You can specify collection options such as maximum size, document validation rules, and others by passing them as arguments to the command method with the create command. For a full list of optional parameters, refer to the MongoDB documentation on the create command.
Get a List of Collections
You can query for a list of collections in a database by calling the collections method. This method returns an array of collection objects in the database.
The following example calls the collections method and iterates over the array to print the results:
database = client.database collection_list = database.collections collection_list.each do |collection| puts collection.name end
To query for only the names of the collections in the database, call the collection_names method as follows:
database = client.database collection_names = database.collection_names collection_names.each do |name| puts name end
Note
The database.collections objects list provides more detailed information (i.e. each collection object can be further queried for metadata), while database.collection_names simply lists the collection names.
Delete a Collection
You can delete a collection from the database by using the drop method.
The following example deletes the test_collection collection:
database = client.database collection = database[:test_collection] collection.drop
Warning
Dropping a Collection Deletes All Data in the Collection
Dropping a collection from your database permanently deletes all documents and all indexes within that collection.
Drop a collection only if the data in it is no longer needed.
Delete a Database
You can delete a database from your MongoDB deployment by using the drop method on a database instance.
The following example deletes the test_database database:
client = Mongo::Client.new(['127.0.0.1:27017'], database: 'test_database') database = client.database database.drop
Warning
Dropping a Database Deletes All Data in the Database
Dropping a database permanently deletes all collections, documents, and indexes within that database.
Drop a database only if you no longer need its data.
Configure Read and Write Operations
You can control how the driver routes read operations by setting a read preference. You can also control options for how the driver waits for acknowledgment of read and write operations on a replica set by setting a read concern and a write concern.
By default, databases inherit these settings from the Mongo::Client instance, and collections inherit them from the database. However, you can change these settings on your database or collection by using one of the following methods:
database.with: Gets the database and applies the new read preference, read concern, and write concern.collection.with: Gets the collection and applies the new read preference, read concern, and write concern.
To change read or write settings with the preceding methods, call the method and pass in the new read preference, read concern, or write concern.
The following example shows how to change the read preference, read concern, and write preference of a database called test-database with the database.with method:
database_with_settings = client.use('test_database').with( read: { mode: :secondary }, read_concern: { level: :local }, write: { w: :majority } )
The following example shows how to change the read preference, read concern, and write concern of a collection:
collection_with_settings = client[:test_collection].with( read: { mode: :secondary }, read_concern: { level: :local }, write: { w: :majority } )
To learn more about the read and write settings, see the following guides in the MongoDB Server manual:
Tag Sets
In MongoDB Server, you can apply key-value tags to replica set members according to any criteria you choose. You can then use those tags to target one or more members for a read operation.
By default, the MongoDB Ruby driver selects primary members for read operations. You can modify this behavior by setting read preferences and, optionally, tag sets.
In the following code example, the tag set passed to the :read parameter instructs the Ruby driver to prefer reads from the New York data center ('dc':'ny') and to fall back to the San Francisco data center ('dc':'sf'):
client = Mongo::Client.new(['IP_ADDRESS_001:27017'], database: 'test', read: { mode: :secondary, tag_sets: [{'dc' => 'ny'}, {'dc' => 'sf'}] }) database = client.database collection = database[:example_collection]
To learn more about replica sets, see the the MongoDB Server manual Replica Set Members page.
Local Threshold
When connecting to a replica set with a non-primary read preference, the driver reads from the nearest eligible replica set member within the latency window. When connecting to a sharded cluster, the driver selects from all reachable mongos instances within the latency window. To learn about read preference modes, see Read
Preference.
By default, the driver uses only those servers whose ping times are within 15 milliseconds of the nearest eligible server.
For example, suppose your replica set has five members and the nearest member has a ping time of 5 milliseconds. With the default localThresholdMS of 15 milliseconds, only members with a ping time of 20 milliseconds or less are within the latency window, as shown in the following table:
Host | Type | Ping Time | Within Latency Window |
|---|---|---|---|
| Primary | 5ms | Yes |
| Secondary | 9ms | Yes |
| Secondary | 13ms | Yes |
| Secondary | 24ms | No |
| Secondary | 42ms | No |
To adjust the latency window, pass the local_threshold option to the Mongo::Client constructor.
The following example specifies a local threshold of 35 milliseconds:
client = Mongo::Client.new( ['IP_ADDRESS_001:27017'], database: 'test_database', read: { mode: :secondary_preferred }, local_threshold: 35 ) database = client.database collection = database[:example_collection] result = collection.find({}).first puts result
In the preceding example, Ruby driver distributes reads between matching members within 35 milliseconds of the closest member's ping time.
Note
Ruby driver ignores the value of local_threshold when communicating with a replica set through a mongos instance. In this case, use the localThreshold command-line option.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: