如何使用 Java 将多个文档插入 MongoDB 集合?
javaobject oriented programmingprogramming更新于 2025/10/8 7:08:17
您可以使用 insertMany() 方法将多个文档插入 MongoDB 中的现有集合。
语法
db.coll.insert(docArray)
其中,
db 是数据库。
coll 是要插入文档的集合(名称)
docArray 是要插入的文档数组。
示例
> use myDatabase()
switched to db myDatabase()
> db.createCollection(sample)
{ "ok" : 1 }
> db.test.insert([{name:"Ram", age:26, city:"Mumbai"}, {name:"Roja", age:28,
city:"Hyderabad"}, {name:"Ramani", age:35, city:"Delhi"}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
使用 Java 程序
在 Java 中,您可以使用 com.mongodb.client.MongoCollection 接口的 insertMany() 方法将文档插入到集合中。此方法接受一个列表(对象),其中包含您要插入的文档作为参数。
因此,使用 Java 程序在 MongoDB 中创建一个集合 −
确保您已在系统中安装了 MongoDB
将以下依赖项添加到 Java 项目的 pom.xml 文件中。
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.2</version> </dependency>
通过实例化 MongoClient 类来创建 MongoDB 客户端。
使用 getDatabase() 方法连接到数据库。
准备要插入的文档。
使用 getCollection() 方法获取要插入文档的集合的对象。
创建一个 List 对象,将所有创建的文档添加到其中。
通过将列表对象作为参数传递来调用 insertMany() 方法。
示例
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingMultipleDocuments {
public static void main( String args[] ) {
//创建 MongoDB 客户端
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//连接数据库
MongoDatabase database = mongo.getDatabase("myDatabase");
//创建集合对象
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Vishakhapatnam");
Document document3 = new Document("name", "Rhim").append("age", 30).append("city", "Delhi");
//插入创建的文档
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
list.add(document3);
collection.insertMany(list);
System.out.println("Documents Inserted");
}
}
输出
Documents Inserted
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

