Quick Start¶
On this page
Prerequisites¶
- A running MongoDB instance on localhost using the default port, 27017.
- The Ruby MongoDB driver. See installation for instructions on how to install the MongoDB driver.
- The following statement at the top of your code:
Make a Connection¶
Use Mongo::Client
to establish a connection to a running MongoDB
instance.
You can also use a URI connection string:
Access a Database and a Collection¶
The following examples demonstrate how to access a particular database and show its collections:
To access a collection, refer to it by name.
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.
To insert multiple documents into a collection, use the
insert_many
method.
Query the Collection¶
Use the find
method to create collection queries.
An empty query filter returns all documents in the collection.
Use a query filter to find only matching documents.
The example should print the following:
See also
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.
The example should print the following:
The following example uses update_many
with a blank query filter
to update all the documents in the collection.
See also
Delete Documents¶
Use the delete_one
or delete_many
methods to delete documents
from a collection (either singly or several at once).
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”.
Create Indexes¶
Use the create_one
or create_many
methods to create indexes
singly or several at once.
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
.
See also