如何使用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