插入多个文档
您可以通过调用来在单个操作中将多个文档插入到集合中insertMany() 方法在 MongoCollection 对象上。要插入它们,请将您的 Document 对象添加到一个 List 中,并将该 List 作为参数传递给 insertMany()。如果您在一个尚不存在的集合上调用 insertMany() 方法,服务器会为您创建它。
在成功插入后,insertMany() 返回一个 InsertManyResult 实例。您可以通过在 InsertManyResult 实例上调用 getInsertedIds() 方法来检索有关您插入的文档的 _id 字段等信息。
如果您的插入操作失败,驱动程序会抛出异常。有关在特定条件下引发的异常类型的信息,请参阅页面底部链接的 insertMany() 的 API 文档。
示例
以下代码片段将多个文档插入到 movies 集合中。
注意
此示例使用连接 URI 连接到 MongoDB 实例。有关连接到您的 MongoDB 实例的更多信息,请参阅连接指南.
// Inserts sample documents describing movies by using the Java driver 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"); // Creates two sample documents containing a "title" field List<Document> movieList = Arrays.asList( new Document().append("title", "Short Circuit 3"), new Document().append("title", "The Lego Frozen Movie")); try { // Inserts sample documents describing movies into the collection InsertManyResult result = collection.insertMany(movieList); // Prints the IDs of the inserted documents System.out.println("Inserted document ids: " + result.getInsertedIds()); // Prints a message if any exceptions occur during the operation } catch (MongoException me) { System.err.println("Unable to insert due to an error: " + me); } } } }
运行示例时,您应该看到以下类似输出,其中包含插入文档的 ObjectId 值
Inserted document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}
有关本页面上提到的类和方法的其他信息,请参阅以下 API 文档