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.
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:
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.MongoExceptionimport com.mongodb.kotlin.client.coroutine.MongoClientimport kotlinx.coroutines.runBlockingimport org.bson.codecs.pojo.annotations.BsonIdimport org.bson.types.ObjectIddata class Movie(@BsonId val id: ObjectId, val title: String, val genres: List<String>)fun main() = runBlocking { 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:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4