如何使用Java将多个文档插入MongoDB集合?
您可以使用**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[] ) {
//Creating a MongoDB client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
//Connecting to the database
MongoDatabase database = mongo.getDatabase("myDatabase");
//Creating a collection object
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");
//Inserting the created documents
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
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP