웹사이트 검색

MongoDB 대량 삽입 - MongoDB insertMany


오늘은 MongoDB 대량 삽입에 대해 살펴보겠습니다. 문서 배열이 매개 변수로 삽입 메서드에 전달되는 대량 삽입 작업을 사용하여 MongoDB에서 한 번에 여러 문서를 삽입할 수 있습니다.

MongoDB 대량 삽입

MongoDB 대량 삽입은 기본적으로 정렬된 삽입을 수행합니다. 특정 지점에서 삽입 중 오류가 발생하면 나머지 문서에 대해서는 삽입이 되지 않습니다. 명령줄을 통해 mongodb 대량 삽입을 사용하여 여러 문서를 삽입하는 방법의 예를 살펴보겠습니다.

MongoDB는 많은 문서를 삽입합니다.


> db.car.insert(
... [
... { _id:1,name:"Audi",color:"Red",cno:"H101",mfdcountry:"Germany",speed:75 },
... { _id:2,name:"Swift",color:"Black",cno:"H102",mfdcountry:"Italy",speed:60 },

... { _id:3,name:"Maruthi800",color:"Blue",cno:"H103",mfdcountry:"India",speed:70 },
... { _id:4,name:"Polo",color:"White",cno:"H104",mfdcountry:"Japan",speed:65 },
... { _id:5,name:"Volkswagen",color:"JetBlue",cno:"H105",mfdcountry:"Rome",speed:80 }       
...  ]
...  )
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 5,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})

이 작업은 5개의 문서를 삽입했습니다. MongoDB는 쿼리에서 사용자가 지정하지 않은 경우 자동으로 id 필드를 생성합니다. "nInserted\ 열은 삽입된 문서의 사용자 수를 알려줍니다. 삽입된 문서를 보려면 아래와 같이 다음 쿼리를 수행합니다.


> db.car.find()
{ "_id" : 1, "name" : "Audi", "color" : "Red", "cno" : "H101", "mfdcountry" : "Germany", "speed" : 75 }
{ "_id" : 2, "name" : "Swift", "color" : "Black", "cno" : "H102", "mfdcountry" : "Italy", "speed" : 60 }
{ "_id" : 3, "name" : "Maruthi800", "color" : "Blue", "cno" : "H103", "mfdcountry" : "India", "speed" : 70 }
{ "_id" : 4, "name" : "Polo", "color" : "White", "cno" : "H104", "mfdcountry" : "Japan", "speed" : 65 }
{ "_id" : 5, "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H105", "mfdcountry" : "Rome", "speed" : 80 }
> 

MongoDB 삽입 작업에 대해 자세히 알아보세요. 삽입하는 동안 사용자가 쿼리의 모든 필드를 제공해야 하는 것은 아닙니다. 이제 일부 필드가 지정되지 않은 경우 삽입이 어떻게 작동하는지 살펴보겠습니다.

일부 필드를 지정하는 MongoDB 대량 삽입 문서


> db.car.insert(
... [
... { _id:6,name:"HondaCity",color:"Grey",cno:"H106",mfdcountry:"Sweden",speed:45 },
... {name:"Santro",color:"Pale Blue",cno:"H107",mfdcountry:"Denmark",speed:55 },
... { _id:8,name:"Zen",speed:54 }
... ]
... )
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
> 

이 예에서 두 번째 문서의 경우 사용자가 id 필드를 지정하지 않고 세 번째 문서의 경우 id, name 및 speed 필드만 쿼리에 제공됩니다. 쿼리는 두 번째 및 세 번째 문서에서 일부 필드가 누락된 경우에도 성공적으로 삽입됩니다. nInserted 열은 세 개의 문서가 삽입되었음을 나타냅니다. find 메소드를 호출하고 삽입된 문서를 확인하십시오.


> db.car.find()
{ "_id" : 1, "name" : "Audi", "color" : "Red", "cno" : "H101", "mfdcountry" : "Germany", "speed" : 75 }
{ "_id" : 2, "name" : "Swift", "color" : "Black", "cno" : "H102", "mfdcountry" : "Italy", "speed" : 60 }
{ "_id" : 3, "name" : "Maruthi800", "color" : "Blue", "cno" : "H103", "mfdcountry" : "India", "speed" : 70 }
{ "_id" : 4, "name" : "Polo", "color" : "White", "cno" : "H104", "mfdcountry" : "Japan", "speed" : 65 }
{ "_id" : 5, "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H105", "mfdcountry" : "Rome", "speed" : 80 }
{ "_id" : 6, "name" : "HondaCity", "color" : "Grey", "cno" : "H106", "mfdcountry" : "Sweden", "speed" : 45 }
{ "_id" : ObjectId("54885b8e61307aec89441a0b"), "name" : "Santro", "color" : "Pale Blue", "cno" : "H107", "mfdcountry" : "Denmark", "speed" : 55 }
{ "_id" : 8, "name" : "Zen", "speed" : 54 }
> 

ID는 "Santro\ 자동차에 대해 MongoDB에서 자동으로 생성됩니다. ID 8의 경우 - 이름과 속도 필드만 삽입됩니다.

정렬되지 않은 문서 삽입

무순서 삽입을 수행하는 동안 특정 지점에서 오류가 발생하면 mongodb는 계속해서 나머지 문서를 배열에 삽입합니다. 예를 들어;


> db.car.insert(
... [
... { _id:9,name:"SwiftDezire",color:"Maroon",cno:"H108",mfdcountry:"New York",speed:40 },
... { name:"Punto",color:"Wine Red",cno:"H109",mfdcountry:"Paris",speed:45 },
...  ],
... { ordered: false }
... )
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
> 

순서가 지정되지 않은 컬렉션임을 나타내는 삽입 쿼리에 순서가 지정된 false가 지정됩니다. db.car.find() 실행


{ "_id" : 1, "name" : "Audi", "color" : "Red", "cno" : "H101", "mfdcountry" : "Germany", "speed" : 75 }
{ "_id" : 2, "name" : "Swift", "color" : "Black", "cno" : "H102", "mfdcountry" : "Italy", "speed" : 60 }
{ "_id" : 3, "name" : "Maruthi800", "color" : "Blue", "cno" : "H103", "mfdcountry" : "India", "speed" : 70 }
{ "_id" : 4, "name" : "Polo", "color" : "White", "cno" : "H104", "mfdcountry" : "Japan", "speed" : 65 }
{ "_id" : 5, "name" : "Volkswagen", "color" : "JetBlue", "cno" : "H105", "mfdcountry" : "Rome", "speed" : 80 }
{ "_id" : 6, "name" : "HondaCity", "color" : "Grey", "cno" : "H106", "mfdcountry" : "Sweden", "speed" : 45 }
{ "_id" : ObjectId("54746407d785e3a05a1808a6"), "name" : "Santro", "color" : "Pale Blue", "cno" : "H107", "mfdcountry" : "Denmark", "speed" : 55 }
{ "_id" : 8, "name" : "Zen", "speed" : 54 }
{ "_id" : 9, "name" : "SwiftDezire", "color" : "Maroon", "cno" : "H108", "mfdcountry" : "New York", "speed" : 40 }
{ "_id" : ObjectId("5474642dd785e3a05a1808a7"), "name" : "Punto", "color" : "Wine Red", "cno" : "H109", "mfdcountry" : "Paris", "speed" : 45 }

문서가 삽입되고 보시다시피 정렬되지 않은 삽입입니다. 삽입 메서드에 오류가 발생하면 결과에 오류를 일으킨 오류 메시지를 나타내는 "WriteResult.writeErrors\ 필드가 포함됩니다.

중복 ID 값 삽입


> db.car.insert({_id:6,name:"Innova"})
WriteResult({
	"nInserted" : 0,
	"writeError" : {
		"code" : 11000,
		"errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: journaldev.car.$_id_  dup key: { : 6.0 }"
	}
})
> 

이 오류는 이미 문서가 포함된 id 6에 대한 문서를 삽입하고 있으므로 값 6의 id에 대해 중복 키 오류가 발생함을 나타냅니다.

MongoDB Bulk.insert() 메서드

이 메서드는 대량 숫자로 삽입 작업을 수행합니다. 버전 2.6부터 도입되었습니다. 구문은 Bulk.insert()입니다. 문서: 삽입할 문서를 지정합니다. 이제 대량 삽입의 예를 살펴보겠습니다.

대량 무순 삽입


> var carbulk = db.car.initializeUnorderedBulkOp();
> carbulk.insert({ name:"Ritz", color:"Grey",cno:"H109",mfdcountry:"Mexico",speed:62});
> carbulk.insert({ name:"Versa", color:"Magenta",cno:"H110",mfdcountry:"France",speed:68});
> carbulk.insert({ name:"Innova", color:"JetRed",cno:"H111",mfdcountry:"Dubai",speed:72});
> carbulk.execute();
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 3,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})
> 

carbulk라는 정렬되지 않은 목록이 생성되고 삽입할 필드, 값으로 삽입 쿼리가 지정됩니다. 데이터가 실제로 데이터베이스에 삽입되었는지 확인하려면 마지막 insert 문 다음에 execute() 메서드를 호출해야 합니다.

MongoDB 대량 주문 삽입

이는 정렬되지 않은 대량 삽입과 유사하지만 initializeOrderedBulkOp 호출을 사용합니다.


>var car1bulk = db.car.initializeOrderedBulkOp();
>car1bulk.insert({ name:"Ertiga", color:"Red",cno:"H112",mfdcountry:"America",speed:65});
>car1bulk.insert({ name:"Quanta", color:"Maroon",cno:"H113",mfdcountry:"Rome",speed:78});
>car1bulk.execute();
BulkWriteResult({
	"writeErrors" : [ ],
	"writeConcernErrors" : [ ],
	"nInserted" : 2,
	"nUpserted" : 0,
	"nMatched" : 0,
	"nModified" : 0,
	"nRemoved" : 0,
	"upserted" : [ ]
})

먼저 carbulk1이라는 자동차 컬렉션의 정렬된 목록을 만든 다음 execute() 메서드를 호출하여 문서를 삽입합니다.

MongoDB 대량 삽입 Java 프로그램

지금까지 쉘 명령을 사용하여 보았던 다양한 대량 작업을 위한 Java 프로그램을 살펴보겠습니다. 아래는 MongoDB 자바 드라이버 버전 2.x를 사용한 대량 삽입을 위한 자바 프로그램입니다.

package com.journaldev.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.BulkWriteResult;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class MongoDBBulkInsert {

	//method that inserts all the documents 
    public static void insertmultipledocs() throws UnknownHostException{
    
    //Get a new connection to the db assuming that it is running    
 
     MongoClient mongoClient = new MongoClient("localhost");
    
     ////use test as a datbase,use your database here 
     DB db=mongoClient.getDB("test");
     
     ////fetch the collection object ,car is used here,use your own 
     DBCollection coll = db.getCollection("car");
     
    //create a new object
    DBObject d1 = new BasicDBObject();
    
    //data for object d1
    d1.put("_id", 11);
    d1.put("name","WagonR");
    d1.put("color", "MetallicSilver");
    d1.put("cno", "H141");
    d1.put("mfdcountry","Australia");
    d1.put("speed",66);
    
    DBObject d2 = new BasicDBObject();
    
    //data for object d2
    d2.put("_id", 12);
    d2.put("name","Xylo");
    d2.put("color", "JetBlue");
    d2.put("cno", "H142");
    d2.put("mfdcountry","Europe");
    d2.put("speed",69);
        
    
    DBObject d3 = new BasicDBObject();
    
    //data for object d3
    d3.put("_id", 13);
    d3.put("name","Alto800");
    d3.put("color", "JetGrey");
    d3.put("cno", "H143");
    d3.put("mfdcountry","Austria");
    d3.put("speed",74);
    
    //create a new list
    List<DBObject> docs = new ArrayList<>();
    
    //add d1,d2 and d3 to list docs
    docs.add(d1);
    docs.add(d2);
    docs.add(d3);
    
    //insert list docs to collection
    coll.insert(docs);
    
    
    //stores the result in cursor
    DBCursor carmuldocs = coll.find();
    
    
    //print the contents of the cursor
     try {
         while(carmuldocs.hasNext()) {
       System.out.println(carmuldocs.next());
        }
    }        finally {
            carmuldocs.close();//close the cursor
    } 
    
    
    }
    
    //method that inserts documents with some fields
    public static void insertsomefieldsformultipledocs() throws UnknownHostException{
    
    //Get a new connection to the db assuming that it is running    
 
     MongoClient mongoClient = new MongoClient("localhost");
    
     ////use test as a datbase,use your database here 
     DB db=mongoClient.getDB("test");
     
     ////fetch the collection object ,car is used here,use your own 
     DBCollection coll = db.getCollection("car");
    
    //create object d1 
    DBObject d1 = new BasicDBObject();
    
    //insert data for name,color and speed
    d1.put("name","Indica");
    d1.put("color", "Silver");
    d1.put("cno", "H154");
    
    
    DBObject d2 = new BasicDBObject();
    
    //insert data for id,name and speed
    d2.put("_id", 43);
    d2.put("name","Astar");
    
    d2.put("speed",79);
        
    
    
    
    List<DBObject> docs = new ArrayList<>();
    docs.add(d1);
    docs.add(d2);
   
    
    coll.insert(docs);
    
    DBCursor carmuldocs = coll.find();
    
     System.out.println("-----------------------------------------------");
     try {
         while(carmuldocs.hasNext()) {
       System.out.println(carmuldocs.next());
        }
    }        finally {
            carmuldocs.close();//close the cursor
    } 
    
    
    }
    
    //method that checks for duplicate documents
    public static void insertduplicatedocs() throws UnknownHostException{
    
    //Get a new connection to the db assuming that it is running    
 
     MongoClient mongoClient = new MongoClient("localhost");
    
     ////use test as a datbase,use your database here 
     DB db=mongoClient.getDB("test");
     
     ////fetch the collection object ,car is used here,use your own 
     DBCollection coll = db.getCollection("car");
     
    DBObject d1 = new BasicDBObject();
    
    //insert duplicate data of id11
    d1.put("_id", 11);
    d1.put("name","WagonR-Lxi");
    
    coll.insert(d1);
    
   
    DBCursor carmuldocs = coll.find();
    
     System.out.println("-----------------------------------------------");
     try {
         while(carmuldocs.hasNext()) {
       System.out.println(carmuldocs.next());
        }
    }        finally {
            carmuldocs.close();//close the cursor
    } 
    
    
    }
    
    //method to perform bulk unordered list
    public static void insertbulkunordereddocs() throws UnknownHostException{
    
    //Get a new connection to the db assuming that it is running    
 
     MongoClient mongoClient = new MongoClient("localhost");
    
     ////use test as a datbase,use your database here 
     DB db=mongoClient.getDB("test");
     
     ////fetch the collection object ,car is used here,use your own 
     DBCollection coll = db.getCollection("car");
     
    DBObject d1 = new BasicDBObject();
    
    
    d1.put("name","Suzuki S-4");
    d1.put("color", "Yellow");
    d1.put("cno", "H167");
    d1.put("mfdcountry","Italy");
    d1.put("speed",54);
    
    DBObject d2 = new BasicDBObject();
    
    
    d2.put("name","Santro-Xing");
    d2.put("color", "Cyan");
    d2.put("cno", "H164");
    d2.put("mfdcountry","Holand");
    d2.put("speed",76);
        
    //intialize and create a unordered bulk
    BulkWriteOperation  b1 = coll.initializeUnorderedBulkOperation();
    
    //insert d1 and d2 to bulk b1
    b1.insert(d1);
    b1.insert(d2);
    
    //execute the bulk
    BulkWriteResult  r1 = b1.execute();
    
    
    
    DBCursor carmuldocs = coll.find();
    
    System.out.println("-----------------------------------------------");
     try {
         while(carmuldocs.hasNext()) {
       System.out.println(carmuldocs.next());
        }
    }        finally {
            carmuldocs.close();//close the cursor
    } 
    
    
    }
    
    //method that performs bulk insert for ordered list
       public static void insertbulkordereddocs() throws UnknownHostException{
    
    //Get a new connection to the db assuming that it is running    
 
     MongoClient mongoClient = new MongoClient("localhost");
    
     ////use test as a datbase,use your database here 
     DB db=mongoClient.getDB("test");
     
     ////fetch the collection object ,car is used here,use your own 
     DBCollection coll = db.getCollection("car");
     
    DBObject d1 = new BasicDBObject();
    
    
    d1.put("name","Palio");
    d1.put("color", "Purple");
    d1.put("cno", "H183");
    d1.put("mfdcountry","Venice");
    d1.put("speed",82);
    
    DBObject d2 = new BasicDBObject();
    
    
    d2.put("name","Micra");
    d2.put("color", "Lime");
    d2.put("cno", "H186");
    d2.put("mfdcountry","Ethopia");
    d2.put("speed",84);
        
    //initialize and create ordered bulk 
    BulkWriteOperation  b1 = coll.initializeOrderedBulkOperation();
    
    b1.insert(d1);
    b1.insert(d2);
    
    //invoking execute
    BulkWriteResult  r1 = b1.execute();
    
    
    
    DBCursor carmuldocs = coll.find();
    
    System.out.println("-----------------------------------");
    
     try {
         while(carmuldocs.hasNext()) {
       System.out.println(carmuldocs.next());
        }
    }        finally {
            carmuldocs.close();//close the cursor
    } 
    
    
    }
    
    
    public static void main(String[] args) throws UnknownHostException{
        
       //invoke all the methods to perform insert operation
       
       insertmultipledocs();
       insertsomefieldsformultipledocs();
       
        insertbulkunordereddocs();
        insertbulkordereddocs();
        insertduplicatedocs();
    }

}

아래는 위 프로그램의 출력입니다.


{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
-----------------------------------------------
{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
-----------------------------------------------
{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d8"} , "name" : "Suzuki S-4" , "color" : "Yellow" , "cno" : "H167" , "mfdcountry" : "Italy" , "speed" : 54}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d9"} , "name" : "Santro-Xing" , "color" : "Cyan" , "cno" : "H164" , "mfdcountry" : "Holand" , "speed" : 76}
-----------------------------------
{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d8"} , "name" : "Suzuki S-4" , "color" : "Yellow" , "cno" : "H167" , "mfdcountry" : "Italy" , "speed" : 54}
{ "_id" : { "$oid" : "548860e803649b8efac5a1d9"} , "name" : "Santro-Xing" , "color" : "Cyan" , "cno" : "H164" , "mfdcountry" : "Holand" , "speed" : 76}
{ "_id" : { "$oid" : "548860e803649b8efac5a1da"} , "name" : "Palio" , "color" : "Purple" , "cno" : "H183" , "mfdcountry" : "Venice" , "speed" : 82}
{ "_id" : { "$oid" : "548860e803649b8efac5a1db"} , "name" : "Micra" , "color" : "Lime" , "cno" : "H186" , "mfdcountry" : "Ethopia" , "speed" : 84}
Exception in thread "main" com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost:27017" , "ok" : 1 , "n" : 0 , "err" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.car.$_id_  dup key: { : 11 }" , "code" : 11000}
	at com.mongodb.CommandResult.getWriteException(CommandResult.java:88)
	at com.mongodb.CommandResult.getException(CommandResult.java:79)
	at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:314)
	at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:189)
	at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
	at com.mongodb.DBCollection.insert(DBCollection.java:93)
	at com.mongodb.DBCollection.insert(DBCollection.java:78)
	at com.mongodb.DBCollection.insert(DBCollection.java:120)
	at com.journaldev.mongodb.MongoDBBulkInsert.insertduplicatedocs(MongoDBBulkInsert.java:163)
	at com.journaldev.mongodb.MongoDBBulkInsert.main(MongoDBBulkInsert.java:304)

MongoDB Java 드라이버 3.x를 사용하는 경우 아래 프로그램을 사용하십시오.

package com.journaldev.mongodb.main;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoDBBulkInsert {

	public static void main(String[] args) throws UnknownHostException {

		// invoke all the methods to perform insert operation

		insertmultipledocs();
		insertsomefieldsformultipledocs();

		insertduplicatedocs();
	}

	// method that inserts all the documents
	public static void insertmultipledocs() throws UnknownHostException {

		// Get a new connection to the db assuming that it is running

		MongoClient mongoClient = new MongoClient("localhost");

		//// use test as a database,use your database here
		MongoDatabase db = mongoClient.getDatabase("test");

		//// fetch the collection object ,car is used here,use your own
		MongoCollection<Document> coll = db.getCollection("car");

		// create a new object
		Document d1 = new Document();

		// data for object d1
		d1.put("_id", 11);
		d1.put("name", "WagonR");
		d1.put("color", "MetallicSilver");
		d1.put("cno", "H141");
		d1.put("mfdcountry", "Australia");
		d1.put("speed", 66);

		Document d2 = new Document();

		// data for object d2
		d2.put("_id", 12);
		d2.put("name", "Xylo");
		d2.put("color", "JetBlue");
		d2.put("cno", "H142");
		d2.put("mfdcountry", "Europe");
		d2.put("speed", 69);

		Document d3 = new Document();

		// data for object d3
		d3.put("_id", 13);
		d3.put("name", "Alto800");
		d3.put("color", "JetGrey");
		d3.put("cno", "H143");
		d3.put("mfdcountry", "Austria");
		d3.put("speed", 74);

		// create a new list
		List<Document> docs = new ArrayList<>();

		// add d1,d2 and d3 to list docs
		docs.add(d1);
		docs.add(d2);
		docs.add(d3);

		// insert list docs to collection
		coll.insertMany(docs);

		// stores the result in cursor
		FindIterable<Document> carmuldocs = coll.find();

		for (Document d : carmuldocs)
			System.out.println(d);

		mongoClient.close();
	}

	// method that inserts documents with some fields
	public static void insertsomefieldsformultipledocs() throws UnknownHostException {

		// Get a new connection to the db assuming that it is running

		MongoClient mongoClient = new MongoClient("localhost");

		//// use test as a datbase,use your database here
		MongoDatabase db = mongoClient.getDatabase("test");

		//// fetch the collection object ,car is used here,use your own
		MongoCollection<Document> coll = db.getCollection("car");

		// create object d1
		Document d1 = new Document();

		// insert data for name,color and speed
		d1.put("name", "Indica");
		d1.put("color", "Silver");
		d1.put("cno", "H154");

		Document d2 = new Document();

		// insert data for id,name and speed
		d2.put("_id", 43);
		d2.put("name", "Astar");

		d2.put("speed", 79);

		List<Document> docs = new ArrayList<>();
		docs.add(d1);
		docs.add(d2);

		coll.insertMany(docs);

		FindIterable<Document> carmuldocs = coll.find();

		System.out.println("-----------------------------------------------");

		for (Document d : carmuldocs)
			System.out.println(d);

		mongoClient.close();

	}

	// method that checks for duplicate documents
	public static void insertduplicatedocs() throws UnknownHostException {

		// Get a new connection to the db assuming that it is running

		MongoClient mongoClient = new MongoClient("localhost");

		//// use test as a database, use your database here
		MongoDatabase db = mongoClient.getDatabase("test");

		//// fetch the collection object ,car is used here,use your own
		MongoCollection<Document> coll = db.getCollection("car");

		Document d1 = new Document();

		// insert duplicate data of id11
		d1.put("_id", 11);
		d1.put("name", "WagonR-Lxi");

		coll.insertOne(d1);

		FindIterable<Document> carmuldocs = coll.find();

		System.out.println("-----------------------------------------------");

		for (Document d : carmuldocs)
			System.out.println(d);

		mongoClient.close();

	}

}