您可以使用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中,可以使用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