Docs Menu

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.

The following snippet inserts multiple documents into the movies collection.

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.

package usage.examples;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertManyResult;
public class InsertMany {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
List<Document> movieList = Arrays.asList(
new Document().append("title", "Short Circuit 3"),
new Document().append("title", "The Lego Frozen Movie"));
try {
InsertManyResult result = collection.insertMany(movieList);
System.out.println("Inserted document ids: " + result.getInsertedIds());
} catch (MongoException me) {
System.err.println("Unable to insert due to an error: " + me);
}
}
}
}

When you run the example, you should see output that resembles the following with the inserted documents' ObjectId values in each of the value fields:

Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}
Tip
Legacy API

If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.

For additional information on the classes and methods mentioned on this page, see the following API Documentation:

←  Insert a DocumentUpdate & Replace Operations →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.