Docs Menu

Docs HomeKotlin Coroutine

Insert Operations

On this page

  • Overview
  • A Note About _id
  • Insert a Single Document
  • Insert Multiple Documents
  • Summary

In this guide, you can learn how to insert documents with the MongoDB Kotlin driver.

You can use MongoDB to retrieve, update, and delete information. To perform any of those operations, that information, such as user profiles and orders, needs to exist in MongoDB. For that information to exist, you need to first perform an insert operation.

An insert operation inserts a single or multiple documents into MongoDB using the insertOne(), insertMany(), and bulkWrite() methods.

The following sections focus on insertOne() and insertMany(). For information on how to use the bulkWrite() method, see our guide on Bulk Operations.

In the following examples, a paint store has an inventory of different colors of paint. This data is modeled with the following Kotlin data class:

data class PaintOrder(
@BsonId val id: ObjectId? = null,
val qty: Int,
val color: String
)

When inserting a document, MongoDB enforces one constraint on your documents by default: each document must contain a unique _id field.

There are two ways to manage this field:

  • You can manage this field yourself, ensuring each value you use is unique.

  • You can let the driver automatically generate unique ObjectId values.

Unless you have provided strong guarantees for uniqueness, we recommend you let the driver automatically generate _id values.

Note

Duplicate _id values violate unique index constraints, resulting in a WriteError.

For additional information on unique indexes, see the manual entry on Unique Indexes.

Use the insertOne() method when you want to insert a single document.

On successful insertion, the method returns an InsertOneResult instance representing the _id of the new document.

The following example creates and inserts a document using the insertOne() method:

val paintOrder = PaintOrder(ObjectId(), 5, "red")
val result = collection.insertOne(paintOrder)
val insertedId = result.insertedId?.asObjectId()?.value
println("Inserted a document with the following id: $insertedId")
Inserted a document with the following id: 60930c39a982931c20ef6cd6

For more information about the methods and classes mentioned in this section, see the following resources:

Use the insertMany() method when you want to insert multiple documents. This method inserts documents in the order specified until an exception occurs, if any.

For example, assume you want to insert the following documents:

{ "color": "red", "qty": 5 }
{ "color": "purple", "qty": 10 }
{ "color": "yellow", "qty": 3 }
{ "color": "blue", "qty": 8 }

If you attempt to insert these documents, a WriteError occurs at the third document and the documents prior to the error get inserted into your collection.

Tip

Use a try-catch block to get an acknowledgment for successfully processed documents before the error occurs. The output consists of documents MongoDB can process:

val result = collection.insertMany(paintOrders)
try {
println("Inserted documents with the following ids: ${result.insertedIds}")
} catch(e: MongoBulkWriteException){
val insertedIds = e.writeResult.inserts.map { it.id.asInt32().value }
println(
"A MongoBulkWriteException occurred, but there are " +
"successfully processed documents with the following ids: $insertedIds"
)
collection.find().collect { println(it) }
}
A MongoBulkWriteException occurred, but there are successfully processed
documents with the following ids: [60930c3aa982931c20ef6cd7, 644ad1378ea29443837a14e9, 60930c3aa982931c20ef6cd8]

If you look inside your collection, you should see the following documents:

{ "color": "red", "qty": 5 }
{ "color": "purple", "qty": 10 }

On successful insertion, the method returns an InsertManyResult instance representing the _id of each new document.

The following example creates and adds two documents to a List, and inserts the List using the insertMany() method:

val paintOrders = listOf(
PaintOrder(ObjectId(), 5, "red"),
PaintOrder(ObjectId(), 10, "purple")
)
val result = collection.insertMany(paintOrders)
println("Inserted a document with the following ids: ${result.insertedIds.toList()}")
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]

For more information about the methods and classes mentioned in this section, see the following resources:

There are three ways to perform an insert operation, but we focused on two:

  • The insertOne() method inserts a single document.

  • The insertMany() method inserts multiple documents.

Both methods automatically generate an _id if you omit the field in your document.

If the insertion is successful, both methods return an instance representing the _id of each new document.

←  Write OperationsDelete Documents →