Insert a Document
You can insert a single document into a collection using the insertOne()
method on a MongoCollection
object. To insert a document, construct a
Document
object that contains the fields and values that you want to
store. If you call the insertOne()
method on a collection that does
not exist yet, the server automatically creates it for you.
Upon a successful insertion, insertOne()
returns an instance of
InsertOneResult
. You can retrieve information such as the _id
field of the document you inserted by calling the getInsertedId()
method on the InsertOneResult
instance.
If your insert operation fails, the driver raises an exception. For more
information on the types of exceptions raised under specific conditions,
see the API documentation for insertOne()
, linked at the bottom of
this page.
Example
The following snippet inserts a single document into the movies
collection.
When you run the example, you should see output with the inserted document's
ObjectId
in the value field:
Note
This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.
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=...}
For additional information on the classes and methods mentioned on this page, see the following API Documentation: