Skip to content

DOCSP-45186: Insert #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions source/includes/write/insert.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'mongo'
end

uri = "<connection string URI>"

Mongo::Client.new(uri) do |client|

# start-db-coll
database = client.use('sample_restaurants')
collection = database[:restaurants]
# end-db-coll

# Inserts a single document
# start-insert-one
document = { name: 'Neighborhood Bar & Grill', borough: 'Queens' }
collection.insert_one(document)
# end-insert-one

# Inserts multiple documents
# start-insert-many
documents = [
{ name: 'Metropolitan Cafe', borough: 'Queens' },
{ name: 'Yankee Bistro', borough: 'Bronx' }
]
collection.insert_many(documents)
# end-insert-many

# Inserts multiple documents while enabling the bypass_document_validation option
# start-insert-options
documents = [
{ name: 'Cloudy Day', borough: 'Brooklyn' },
{ name: 'Squall or Shine', borough: 'Staten Island' }
{ name: 'Rose Field', borough: 'Queens' }
]
options = { bypass_document_validation: true }
collection.insert_many(documents, options)
# end-insert-options
end
167 changes: 167 additions & 0 deletions source/write/insert.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
.. _ruby-write-insert:

================
Insert Documents
================

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

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: code example, write, save, create

Overview
--------

In this guide, you can learn how to use the {+driver-short+} to add
documents to a MongoDB collection by performing **insert operations**.

An insert operation inserts one or more documents into a MongoDB collection.
You can perform an insert operation by using the following methods:

- ``insert_one`` to insert a single document
- ``insert_many`` to insert one or more documents

Sample Data
~~~~~~~~~~~

The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants``
database from the :atlas:`Atlas sample datasets </sample-data>`. To access this collection
from your {+language+} application, create a ``Mongo::Client`` object that connects to an Atlas cluster
and assign the following values to your ``database`` and ``collection`` variables:

.. literalinclude:: /includes/write/insert.rb
:language: ruby
:dedent:
:start-after: start-db-coll
:end-before: end-db-coll

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the
:atlas:`Get Started with Atlas </getting-started>` guide.

The _id Field
-------------

In a MongoDB collection, each document *must* contain an ``_id`` field
with a unique field value.

MongoDB allows you to manage this field in two ways:

- Set the ``_id`` field for each document yourself, ensuring each
value is unique.
- Let the driver automatically generate unique ``BSON::ObjectId``
values for each document ``_id`` field.

Unless you can guarantee uniqueness, we recommend
letting the driver automatically generate ``_id`` values.

.. note::

Duplicate ``_id`` values violate unique index constraints, which
causes the driver to return an error.

To learn more about the ``_id`` field, see the
:manual:`Unique Indexes </core/index-unique/>` guide in the {+mdb-server+} manual.

To learn more about document structure and rules, see the
:manual:`Documents </core/document>` guide in the {+mdb-server+} manual.

Insert One Document
-------------------

To add a single document to a MongoDB collection, call the ``insert_one``
method and pass the document you want to insert.

The following example inserts a document into the ``restaurants`` collection:

.. literalinclude:: /includes/write/insert.rb
:language: ruby
:start-after: start-insert-one
:end-before: end-insert-one
:dedent:
:copyable:

Insert Multiple Documents
-------------------------

To add multiple documents to a MongoDB collection, call the ``insert_many``
method and pass a list of documents you want to insert.

The following example inserts two documents into the ``restaurants`` collection:

.. literalinclude:: /includes/write/insert.rb
:language: ruby
:start-after: start-insert-many
:end-before: end-insert-many
:dedent:
:copyable:

Modify Insert Behavior
----------------------

You can pass a ``Hash`` object as a parameter to the ``insert_one``
method to set options to configure the insert operation. If you don't specify any options,
the driver performs the insert operation with default settings.

The following table describes the options you can set to
configure the ``insert_one`` operation:

.. list-table::
:widths: 30 70
:header-rows: 1

* - Option
- Description

* - ``bypass_document_validation``
- | Instructs the driver whether to ignore document-level validation. For more information,
see :manual:`Schema Validation </core/schema-validation>` in the {+mdb-server+} manual.
| Defaults to ``false``.

* - ``comment``
- | Sets a comment to attach to the operation. For more information, see the :manual:`insert command
fields </reference/command/insert/#command-fields>` guide in the {+mdb-server+} manual.

* - ``session``
- | Sets the session to use for the operation. To learn more about sessions, see
:manual:`Client Sessions and Causal Consistency Guarantees </core/read-isolation-consistency-recency/#std-label-sessions>`
in the {+mdb-server+} manual.

* - ``write_concern``
- | Sets the write concern for the operation. For more information, see the
:manual:`Write Concern </core/write-concern>` guide in the {+mdb-server+} manual.

You can set the preceding settings on the ``insert_many`` method
by passing a ``Hash`` as a parameter to the method call. You can also use the
``ordered`` option to specify the order in which the driver
inserts documents into MongoDB.

Example
~~~~~~~

The following code uses the ``insert_many`` method to insert
three new documents into a collection. Because the ``bypass_document_validation``
option is enabled, this insert operation bypasses document-level validation.

.. literalinclude:: /includes/write/insert.rb
:language: ruby
:start-after: start-insert-options
:end-before: end-insert-options
:dedent:
:copyable:

Additional Information
----------------------

To learn more about any of the methods discussed in this
guide, see the following API documentation:

- `insert_one <{+api-root+}/Mongo/Collection.html#insert_one-instance_method>`_
- `insert_many <{+api-root+}/Mongo/Collection.html#insert_many-instance_method>`_
Loading