docs/tutorials/quick-start.txt
***********
Quick Start
***********
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Prerequisites
=============
- A running MongoDB instance on localhost using the default port, 27017.
- The Ruby MongoDB driver. See :ref:`installation <installation>`
for instructions on how to install the MongoDB driver.
- The following statement at the top of your code:
.. code-block:: ruby
require 'mongo'
Make a Connection
=================
Use ``Mongo::Client`` to establish a connection to a running MongoDB
instance.
.. code-block:: ruby
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
You can also use a URI connection string:
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
.. seealso::
:ref:`Connect to a replica set <connect-replica-set>`,
:ref:`Connect to a sharded cluster <connect-sharded-cluster>`,
:ref:`Client options <client-options>`
Access a Database and a Collection
==================================
The following examples demonstrate how to access a particular database
and show its collections:
.. code-block:: ruby
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
db = client.database
db.collections # returns a list of collection objects
db.collection_names # returns a list of collection names
db.list_collections # returns a list of collection metadata hashes
To access a collection, refer to it by name.
.. code-block:: ruby
collection = client[:restaurants]
If the collection does not exist, the server will create it the first
time you put data into it.
Insert a Document
=================
To insert a single document into a collection, use the
``insert_one`` method.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
doc = {
name: 'Steve',
hobbies: [ 'hiking', 'tennis', 'fly fishing' ],
siblings: {
brothers: 0,
sisters: 1
}
}
result = collection.insert_one(doc)
result.n # returns 1, because one document was inserted
To insert multiple documents into a collection, use the
``insert_many`` method.
.. code-block:: ruby
docs = [ { _id: 1, name: 'Steve',
hobbies: [ 'hiking', 'tennis', 'fly fishing' ],
siblings: { brothers: 0, sisters: 1 } },
{ _id: 2, name: 'Sally',
hobbies: ['skiing', 'stamp collecting' ],
siblings: { brothers: 1, sisters: 0 } } ]
result = collection.insert_many(docs)
result.inserted_count # returns 2 because two documents were inserted
Query the Collection
====================
Use the ``find`` method to create collection queries.
An empty query filter returns all documents in the collection.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.find.each do |document|
#=> Yields a BSON::Document.
end
Use a query filter to find only matching documents.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
puts collection.find( { name: 'Sally' } ).first
The example should print the following:
.. code-block:: javascript
{"_id" => 2, "name" => "Sally", "hobbies" => ["skiing", "stamp collecting"], "siblings" => { "brothers": 1, "sisters": 0 } }
Query nested documents by specifying the keys and values you want
to match.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
puts collection.find("siblings.sisters": 1 ).first
The example should print the following:
.. code-block:: javascript
{"_id"=>1, "name"=>"Steve", "hobbies"=>["hiking", "tennis", "fly fishing"], "siblings"=>{"brothers"=>0, "sisters"=>1}}
.. seealso::
:ref:`Query Options<query-options>`, :ref:`Read Preference<read-preference>`
Update Documents
================
There are several update methods, including ``update_one`` and
``update_many``. ``update_one`` updates a single document, while
``update_many`` updates multiple documents at once.
Both methods take as arguments a query filter document and a second
document with the update data. Use ``$set`` to add or update a
particular field or fields. Without ``$set``, the entire existing
document is replaced with the update data.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.update_one( { 'name' => 'Sally' }, { '$set' => { 'phone_number' => "555-555-5555" } } )
puts collection.find( { 'name' => 'Sally' } ).first
The example should print the following:
.. code-block:: javascript
{"_id" => 2, "name" => "Sally", "hobbies" => ["skiing", "stamp collecting"], "phone_number" => "555-555-5555"}
The following example uses ``update_many`` with a blank query filter
to update all the documents in the collection.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.update_many( {}, { '$set' => { 'age' => 36 } } )
puts result.modified_count # returns 2 because 2 documents were updated
.. seealso::
:ref:`Other update options<updating>`
Delete Documents
================
Use the ``delete_one`` or ``delete_many`` methods to delete documents
from a collection (either singly or several at once).
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.delete_one( { name: 'Steve' } )
puts result.deleted_count # returns 1 because one document was deleted
The following example inserts two more records into the collection,
then deletes all the documents with a ``name`` field which
matches a regular expression to find a string which begins with "S".
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.insert_many([ { _id: 3, name: "Arnold" }, { _id: 4, name: "Susan" } ])
puts collection.count # counts all documents in collection
result = collection.delete_many({ name: /$S*/ })
puts result.deleted_count # returns the number of documents deleted
Create Indexes
==============
Use the ``create_one`` or ``create_many`` methods to create indexes
singly or several at once.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.indexes.create_one({ name: 1 }, unique: true)
Use the ``create_many`` method to create several indexes with one
statement. Note that when using ``create_many``, the syntax is
different from ``create_one``.
.. code-block:: ruby
client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.indexes.create_many([
{ key: { name: 1 } , unique: true },
{ key: { hobbies: 1 } },
])
.. seealso::
:ref:`Index options <index-options>`
Complete Sample App
===================
A sample app using the Ruby driver for several common use cases
is available for download from
`GitHub <https://github.com/steveren/ruby-driver-sample-app>`_.