java 操作mongo进行批量插入
时间: 2023-02-14 20:35:55 浏览: 411
可以使用 MongoDB Java 驱动程序中的 MongoCollection
类的 insertMany
方法执行批量插入。这个方法接受一个文档列表作为参数,并将这些文档插入到指定的 MongoDB 集合中。
例如:
import com.mongodb.client.MongoCollection;
import org.bson.Document;
// 连接到数据库
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
// 获取集合
MongoCollection<Document> collection = database.getCollection("myCollection");
// 创建要插入的文档列表
List<Document> documents = new ArrayList<Document>();
documents.add(new Document("name", "Alice").append("age", 30));
documents.add(new Document("name", "Bob").append("age", 35));
// 执行批量插入
collection.insertMany(documents);
// 关闭连接
mongoClient.close();
注意:在执行批量插入之前,需要先连接到 MongoDB 服务器并选择要插入文档的数据库和集合。
相关推荐


















