Overview
In this guide, you can learn how to use the Kotlin 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 following methods:
insertOne()to insert a single documentinsertMany()to insert one or more documents
Sample Data
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( val id: ObjectId? = null, val qty: Int, val color: 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
_idfield value is unique.You can let the driver automatically generate a unique
ObjectIdvalue for each document_id. If you do not manually set an_idvalue 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
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 by 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
Insert Multiple Documents
To add multiple documents to a MongoDB collection, use the insertMany()
method and pass a list of documents you want to add. The
insertMany() method inserts documents in the order specified until
an exception occurs, if any.
If successful, 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 by using the insertMany() method:
val paintOrders = listOf( PaintOrder(ObjectId(), 5, "red"), PaintOrder(ObjectId(), 10, "purple") ) val result = collection.insertMany(paintOrders) println("Inserted documents with the following ids: ${result.insertedIds.toList()}")
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
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.
Fully Runnable Examples
The following sections provide fully runnable examples that demonstrate how to
insert documents by using the insertOne() and insertMany()
methods.
Sample Data
The examples in this section use the sample_movies.movies collection
from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Mongodb Get Started guide.
insertOne() Example: Full File
The following example connects to a MongoDB cluster, creates a
MongoClient object, and inserts a single document into the
movies collection by using the insertOne() method:
import com.mongodb.MongoException import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking import org.bson.codecs.pojo.annotations.BsonId import org.bson.types.ObjectId data class Movie( val id: ObjectId, val title: String, val genres: List<String>) fun main() = runBlocking { // Replace the uri string with your MongoDB deployment's connection string val uri = "<connection string uri>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Movie>("movies") try { val result = collection.insertOne( Movie(ObjectId(), "Ski Bloopers", listOf("Documentary", "Comedy")) ) println("Success! Inserted document id: " + result.insertedId) } catch (e: MongoException) { System.err.println("Unable to insert due to an error: $e") } mongoClient.close() }
Success! Inserted document id: BsonObjectId{value=...}
insertMany() Example: Full File
The following example connects to a MongoDB cluster, creates a
MongoClient object, and inserts multiple documents into the
movies collection by using the insertMany() method:
import com.mongodb.MongoException import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking data class Movie(val title: String) fun main() = runBlocking { // Replace the uri string with your MongoDB deployment's connection string val uri = "<connection string uri>" val mongoClient = MongoClient.create(uri) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Movie>("movies") val movieList = listOf( Movie("Short Circuit 3"), Movie("The Lego Frozen Movie") ) try { val result = collection.insertMany(movieList) println("Success! Inserted document ids: " + result.insertedIds) } catch (e: MongoException) { System.err.println("Unable to insert due to an error: $e") } mongoClient.close() }
Success! Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: