Insert Multiple Documents
You can insert multiple documents into a collection in a single
operation by calling the insertMany()
method on a MongoCollection
object. To insert them, add your Document
objects to a List
and pass
that List
as an argument to insertMany()
. If you call the insertMany()
method
on a collection that does not exist yet, the server creates it for you.
Upon successful insertion, insertMany()
returns an instance of
InsertManyResult
. You can retrieve information such as the _id
fields of the documents you inserted by calling the getInsertedIds()
method on the InsertManyResult
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 insertMany()
, linked at the bottom of
this page.
Example
The following snippet inserts multiple documents into the movies
collection.
When you run the example, you should see output with the inserted documents'
ObjectId
values in each of the value fields:
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 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=...}}
For additional information on the classes and methods mentioned on this page, see the following API Documentation: