Docs Menu
Docs Home
/ / /
Kotlin Sync Driver
/

Insert Documents

On this page

  • Overview
  • Sample Data
  • The _id Field
  • Insert One Document
  • Insert Multiple Documents
  • Modify Insert Behavior
  • Modify Insert Example
  • Return Value
  • Additional Information
  • API Documentation

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.

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)

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 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.

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)

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)

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
bypassDocumentValidation()
If set to true, allows the driver to ignore document-level validation.
Defaults to false.
comment()
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
ordered()
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.

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)

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
getInsertedId()
Indicates the _id value of the inserted document.
wasAcknowledged()
Returns true if the server acknowledges the result.

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

Method
Description
getInsertedIds()
Indicates the _id values of the inserted documents.
wasAcknowledged()
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.

For runnable code examples that demonstrate how to insert documents by using the Kotlin Sync driver, see Write Data to MongoDB.

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

Back

Write Data to MongoDB