Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách chèn nhiều Document vào Collection MongoDB bằng Java

Để chèn nhiều document cùng lúc, MongoDB shell dùng insert() với mảng document, còn Java driver cung cấp insertMany().

Cú pháp (Shell)

db.coll.insert(docArray)

Ví dụ Shell

> db.test.insert([{name:"Ram", age:26, city:"Mumbai"}, {name:"Roja", age:28, city:"Hyderabad"}, {name:"Ramani", age:35, city:"Delhi"}])
BulkWriteResult({ "nInserted" : 3, ... })

Chương trình Java

Phương thức insertMany() của MongoCollection nhận một List<Document>.

Các bước: tạo client, kết nối DB, chuẩn bị các Document, thêm vào List, gọi insertMany(list).

Ví dụ Java

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[]) {
        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");
    }
}

Kết quả

Documents Inserted