mongodb/mongo-ruby-driver

View on GitHub
docs/reference/database-tasks.txt

Summary

Maintainability
Test Coverage
*********
Databases
*********

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

The driver provides various helpers on database objects for executing
commands, getting collection lists, and administrative tasks.


List Collections
================

To get a list of collections or collection names for a database, use
``collections`` and ``collection_names``, respectively.

.. code-block:: ruby

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

  database.collections      # Returns an array of Collection objects.
  database.collection_names # Returns an array of collection names as strings.


.. _arbitrary-commands:

Arbitrary Comands
=================

To execute any command on the database, use the ``command`` method.

.. code-block:: ruby

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

  result = database.command(:ping => 1)
  result.first # Returns the BSON::Document returned from the server.

.. note::

  Specifying server API version as a client option and also specifying
  any of the respective command parameters to the ``command`` method
  (i.e. the ``apiVersion``, ``apiStrict`` and ``apiDeprecationErrors``
  command parameters) at the same time is not allowed and will produce an error.


Drop Database
=============

To drop a database, use the ``drop`` method.

.. code-block:: ruby

  client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
  client.database.drop