-
Notifications
You must be signed in to change notification settings - Fork 10
DOCSP-41127: insert docs #20
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
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: rename collection to "restaurants" so that it is clearer that we're inserting into the restaurants collection, especially since the user doesn't get to see the code declaring the collection/getting the collection There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if you do this, change the code that says "collection" to "restaurants" There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would prefer not to do this, as different pages use different sample data (this repo uses restaurants and movies off the top of my head). I dont think that the code examples here are supposed to necessarily be runnable, moreso demonstrate/explain the API for performing certain tasks. I think keeping the variable name as |
||
|
||
// 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 | ||
|
||
} | ||
|
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 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: Clarify that the parameter is the second parameter that you pass into the method/last paramater |
||||||
that sets options to configure the insert operation. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: Introduce InsertOneOptions as the name of the options class somewhere here. Currently, you only introduce it when you introduce the table, which is a little confusing. |
||||||
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 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Q: Is ordered() only applicable to insertmanyoptions? S: instead of having the ordered method be in the copy where people might overlook it, make a new table with just one entry and have the ordered() method in the table with a description. |
||||||
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 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It might be confusing to use option and method interchangeably, I will workshop different phrasing. |
||||||
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 | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. S: Make these a table rather than a bulleted list, for consistency Applies to all |
||||||
- ``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: |
Uh oh!
There was an error while loading. Please reload this page.