Skip to content

Commit

Permalink
DOCSP-41127: insert docs
Browse files Browse the repository at this point in the history
  • Loading branch information
rustagir committed Jul 24, 2024
1 parent 0379473 commit 843f43a
Show file tree
Hide file tree
Showing 5 changed files with 276 additions and 10 deletions.
2 changes: 1 addition & 1 deletion source/includes/write/delete.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ fun main() {

val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Movie>("restaurants")
val collection = database.getCollection<Restaurant>("restaurants")

// start-delete-one
val filter = eq(Restaurant::name.name, "Happy Garden")
Expand Down
42 changes: 42 additions & 0 deletions source/includes/write/insert.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import com.mongodb.client.model.DeleteOptions
import com.mongodb.client.model.Filters.*
import com.mongodb.client.model.InsertManyOptions
import com.mongodb.kotlin.client.MongoClient

// start-data-class
data class Restaurant(val name: String, val borough: String)
// end-data-class

fun main() {
val uri = "<connection string>"

val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")

// start-insert-one
val doc = Restaurant("Sea Shell Bar", "Queens")
val result = collection.insertOne(doc)
// end-insert-one

// start-insert-many
val docs = listOf(
Restaurant("Full Moon Grill", "Queens"),
Restaurant("King's Cup", "Manhattan"),
)

val result = collection.insertMany(docs)
// end-insert-many

// start-insert-opts
val opts = InsertManyOptions().bypassDocumentValidation(true)
val docs = listOf(
Restaurant("Full Moon Grill", "Queens"),
Restaurant("King's Cup", "Manhattan"),
)

val result = collection.insertMany(docs, opts)
// end-insert-opts

}

14 changes: 7 additions & 7 deletions source/write-operations.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ Write Data to MongoDB
:titlesonly:
:maxdepth: 1

/write/insert
/write/delete

..
/write/insert
/write/update
/write/replace
/write/bulk-write
Expand All @@ -40,8 +40,8 @@ methods that you can use to write data to MongoDB by using the

.. tip::

To learn more about any of the methods shown on this page, see the link
provided in each section.
To learn more about any of the methods shown on this page, see the link
provided in each section.

To use an example from this page, copy the code example into the
:ref:`sample application <kotlin-sync-write-sample>` or your own application.
Expand Down Expand Up @@ -71,8 +71,8 @@ collection:
:copyable:
:dedent:

.. To learn more about the ``insert_one()`` method, see the :ref:`Insert Documents
.. <kotlin-sync-write-insert>` guide.
To learn more about the ``insertOne()`` method, see the :ref:`Insert Documents
<kotlin-sync-write-insert>` guide.

Insert Multiple
---------------
Expand All @@ -87,8 +87,8 @@ collection:
:copyable:
:dedent:

.. To learn more about the ``insert_many()`` method, see the :ref:`Insert Documents
.. <kotlin-sync-write-insert>` guide.
To learn more about the ``insertMany()`` method, see the :ref:`Insert Documents
<kotlin-sync-write-insert>` guide.

Update One
----------
Expand Down
7 changes: 5 additions & 2 deletions source/write/delete.txt
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ configure a ``DeleteOptions`` instance:
:widths: 30 70
:header-rows: 1

* - Property
* - Method
- Description

* - ``collation()``
Expand Down Expand Up @@ -140,6 +140,9 @@ configure a ``DeleteOptions`` instance:
fields </reference/command/delete/#command-fields>` guide in the
{+mdb-server+} manual for more information.

Modify Delete Example
`````````````````````

The following code creates options and uses the ``comment()`` method to
add a comment to the delete operation. Then, the example uses the
``deleteMany()`` method to delete all documents in the ``restaurants``
Expand Down Expand Up @@ -185,7 +188,7 @@ API Documentation
~~~~~~~~~~~~~~~~~

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

- `deleteOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-one.html>`__
- `deleteMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/delete-many.html>`__
Expand Down
221 changes: 221 additions & 0 deletions source/write/insert.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
.. _kotlin-sync-write-insert:

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

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

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

.. meta::
:keywords: code examples, 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 ``insertOne()`` and
``insertMany()`` methods.

.. .. tip:: Interactive Lab

.. This page includes a short interactive lab that demonstrates how to
.. insert data by using the ``insertOne()`` method. You can complete this
.. lab directly in your browser window without installing MongoDB or a code editor.

.. To start the lab, click the :guilabel:`Open Interactive Tutorial` button at the
.. top of the page. To expand the lab to a full-screen format, click the
.. full-screen button (:guilabel:`⛶`) in the top-right corner of the lab pane.

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

The examples in this guide use the ``sample_restaurants.restaurants`` collection
from the :atlas:`Atlas sample datasets </sample-data>`. 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 documents in this collection are modeled by the following {+language+} data class:

.. literalinclude:: /includes/write/delete.kt
:start-after: start-data-class
:end-before: end-data-class
:language: kotlin
:copyable:
:dedent:

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

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

MongoDB allows you to manage this field in two ways:

- You can set this field for each document yourself, ensuring each
``_id`` field value is unique.
- You can let the driver automatically generate a unique ``ObjectId``
value for each document ``_id``. If you do not manually set an
``_id`` value for a document, the driver populates the field
with an ``ObjectId``.

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

.. note:: Duplicate _id Errors

Setting duplicate ``_id`` values in a collection violates unique
index constraints, which causes the driver to return a ``WriteError`` from
the ``insertOne()`` method or a ``BulkWriteError`` from the
``insertMany()`` method.

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 ``insertOne()``
method and pass the document you want to add.

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

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

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

To add multiple documents to a MongoDB collection, user the ``insertMany()``
method and pass a list of documents you want to add.

The following example inserts a list of documents into the
``restaurants`` collection:

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

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

The ``insertOne()`` method optionally accepts a parameter
that sets 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 setter methods that you can use to
configure an ``InsertOneOptions`` instance:

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

* - Property
- Description

* - ``bypassDocumentValidation()``
- | If set to ``true``, allows the driver to ignore
:manual:`document-level validation </core/schema-validation>`.
| 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 for more information.

You can set the preceding settings on the ``insertMany()`` method
by configuring an ``InsertManyOptions`` instance. You can also use the
``ordered()`` method setter method to specify the order in which the driver
inserts documents into MongoDB. If set to ``true``, the driver sends documents to the
server in the order provided. If an error occurs, the driver and server
cancel all remaining insert operations. The driver performs ordered
inserts by default.

Modify Insert Example
~~~~~~~~~~~~~~~~~~~~~

The following code creates options and uses the ``bypassDocumentValidation()`` method to
ignore document validation rules. Then, the example uses the
``insertMany()`` method to add new documents to the ``restaurants``
collection.

.. literalinclude:: /includes/write/insert.kt
:start-after: start-insert-opts
:end-before: end-insert-opts
:language: kotlin
:copyable:
:dedent:

Return Value
------------

The ``insertOne()`` method returns an ``InsertOneResult`` instance, and
the ``insertMany()`` method returns an ``InsertManyResult`` instance.

You can use the following methods to retrieve information from
an ``InsertOneResult`` instance:

- ``getInsertedId()``, which indicates the ``_id`` value of the inserted document
- ``wasAcknowledged()``, which returns ``true`` if the server
acknowledges the result

You can use the following methods to retrieve information from
an ``InsertOneResult`` instance:

- ``getInsertedIds()``, which indicates the ``_id`` values of the inserted documents
- ``wasAcknowledged()``, which returns ``true`` if the server
acknowledges the result

.. note::

If the ``wasAcknowledged()`` method returns ``false``, trying to
access the ``_id`` values results in an
``InvalidOperation`` exception. The driver cannot
determine these values if the server does not acknowledge the write
operation.

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

For runnable code examples that demonstrate how to insert documents by
using the {+driver-short+}, see :ref:`kotlin-sync-write`.

API Documentation
~~~~~~~~~~~~~~~~~

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

- `insertOne() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-one.html>`__
- `insertMany() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/insert-many.html>`__
- `InsertOneOptions <{+core-api+}/com/mongodb/client/model/InsertOneOptions.html>`__
- `InsertManyOptions <{+core-api+}/com/mongodb/client/model/InsertManyOptions.html>`__
- `InsertOneResult <{+core-api+}/com/mongodb/client/result/InsertOneResult.html>`__
- `InsertManyResult <{+core-api+}/com/mongodb/client/result/InsertManyResult.html>`__

.. .. instruqt::
.. :title: insertOne() Lesson
.. :drawer:

0 comments on commit 843f43a

Please sign in to comment.