Overview
In this guide, you can learn how to use the Kotlin Sync driver 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.
Sample Data
The examples in this guide use the sample_restaurants.restaurants
collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
The documents in this collection are modeled by the following Kotlin data class:
data class Restaurant(val name: String, val borough: String)
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 anObjectId
.
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 Unique Indexes guide in the MongoDB Server manual.
To learn more about document structure and rules, see the Documents guide in the MongoDB 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:
val doc = Restaurant("Sea Shell Bar", "Queens") val result = collection.insertOne(doc)
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:
val docs = listOf( Restaurant("Full Moon Grill", "Queens"), Restaurant("King's Cup", "Manhattan"), ) val result = collection.insertMany(docs)
Modify Insert Behavior
The insertOne()
method optionally accepts an InsertOneOptions
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. Pass options as the last parameter to the insertOne()
method.
The following table describes the setter methods that you can use to configure an InsertOneOptions
instance:
Method | Description |
---|---|
| If set to true , allows the driver to ignore document-level validation.Defaults to false . |
| Sets a comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB 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:
Method | Description |
---|---|
| If set to true , the driver sends documents to the server in the order provided. If an error occurs, the driver cancels all remaining insert operations.Defaults to true . |
Pass options as the last parameter to the insertMany()
method.
Modify Insert Example
The following code uses the bypassDocumentValidation()
method to set the option to ignore document validation rules. Then, the example uses the insertMany()
method to add new documents to the restaurants
collection.
val opts = InsertManyOptions().bypassDocumentValidation(true) val docs = listOf( Restaurant("Full Moon Grill", "Queens"), Restaurant("King's Cup", "Manhattan"), ) val result = collection.insertMany(docs, opts)
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:
Method | Description |
---|---|
| Indicates the |
| Returns |
You can use the following methods to retrieve information from an InsertOneResult
instance:
Method | Description |
---|---|
| Indicates the |
| Returns |
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 Kotlin Sync driver, see Write Data to MongoDB.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: