“文档” 菜单
文档首页
/ / /
Java (Sync) 驱动程序
/ /

插入多个文档

您可以通过调用对象上的insertMany() MongoCollection方法,在单个操作中将多个文档插入到一个collection中。要插入它们,请将Document对象添加到List中,并将List作为参数传递给insertMany() 。 如果对尚不存在的集合调用insertMany()方法,服务器则会创建该集合。

插入成功后, insertMany()会返回InsertManyResult的实例。 您可以通过对实例InsertManyResult调用getInsertedIds()方法来检索信息,例如所插入文档的_id字段。

如果插入操作失败,驱动程序会引发异常。 有关特定条件下引发的异常类型的更多信息,请参阅本页底部链接的insertMany()的 API 文档。

以下代码段将多个文档插入到moviescollection中。

注意

此示例使用连接 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

如果您使用的是传统 API,请参阅我们的常见问题页面,了解需要对该代码示例进行哪些更改。

有关此页面上提及的类和方法的更多信息,请参阅以下 API 文档:

  • insertMany()

  • 文档

  • InsertManyResult

← 插入文档