MongoDB 批量插入 - MongoDB insertMany

在 MongoDB 中,可以使用大量插入操作同时插入多个文档,其中一组文档作为参数传递到插入方法中。

MongoDB 大量插入

默认情况下,MongoDB 大量插入执行顺序的插入。如果在某个时刻在插入过程中出现错误,则插入不会发生在剩余的文档中。

MongoDB 插入许多文档

 1> db.car.insert(
 2... [
 3... { _id:1,name:"Audi",color:"Red",cno:"H101",mfdcountry:"Germany",speed:75 },
 4... { _id:2,name:"Swift",color:"Black",cno:"H102",mfdcountry:"Italy",speed:60 },
 5
 6... { _id:3,name:"Maruthi800",color:"Blue",cno:"H103",mfdcountry:"India",speed:70 },
 7... { _id:4,name:"Polo",color:"White",cno:"H104",mfdcountry:"Japan",speed:65 },
 8... { _id:5,name:"Volkswagen",color:"JetBlue",cno:"H105",mfdcountry:"Rome",speed:80 }       
 9...  ]
10...  )
11BulkWriteResult({
12    "writeErrors" : [ ],
13    "writeConcernErrors" : [ ],
14    "nInserted" : 5,
15    "nUpserted" : 0,
16    "nMatched" : 0,
17    "nModified" : 0,
18    "nRemoved" : 0,
19    "upserted" : [ ]
20})

此操作插入了五个文档 MongoDB 会自动创建一个 id 字段,如果不是用户在查询中指定的。**nInserted**列告诉用户插入的文档数量。

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

閱讀更多關於 MongoDB 查找MongoDB 插入的操作。在插入時,使用者不需要在查詢中提供所有欄位。

MongoDB 大量插入指定某些字段的文档

 1> db.car.insert(
 2... [
 3... { _id:6,name:"HondaCity",color:"Grey",cno:"H106",mfdcountry:"Sweden",speed:45 },
 4... {name:"Santro",color:"Pale Blue",cno:"H107",mfdcountry:"Denmark",speed:55 },
 5... { _id:8,name:"Zen",speed:54 }
 6... ]
 7... )
 8BulkWriteResult({
 9    "writeErrors" : [ ],
10    "writeConcernErrors" : [ ],
11    "nInserted" : 3,
12    "nUpserted" : 0,
13    "nMatched" : 0,
14    "nModified" : 0,
15    "nRemoved" : 0,
16    "upserted" : [ ]
17})
18>

在此示例中,对于第二个文档,ID 字段不是由用户指定,而对于第三个文档,只有 id、名称和速度字段在查询中提供。

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

请注意,ID是由MongoDB自动生成的汽车Santro。对于id 8 - 只插入名称和速度字段。

插入未分类的文档

在执行无序插入时,如果在某个时刻出现错误,mongodb 会继续将剩余的文档插入到一个数组中。

 1> db.car.insert(
 2... [
 3... { _id:9,name:"SwiftDezire",color:"Maroon",cno:"H108",mfdcountry:"New York",speed:40 },
 4... { name:"Punto",color:"Wine Red",cno:"H109",mfdcountry:"Paris",speed:45 },
 5...  ],
 6... { ordered: false }
 7... )
 8BulkWriteResult({
 9    "writeErrors" : [ ],
10    "writeConcernErrors" : [ ],
11    "nInserted" : 2,
12    "nUpserted" : 0,
13    "nMatched" : 0,
14    "nModified" : 0,
15    "nRemoved" : 0,
16    "upserted" : [ ]
17})
18>

排序的 false 被指定在插入查询中,表示它是一个未排序的集合。

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

如果插入方法遇到错误,结果包括WriteResult.writeErrors字段,表示导致失败的错误消息。

插入重复 id 值

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

该错误表明,我们正在插入一个已包含文档的 id 6 文档,因此丢弃了值 6 的 id 的重复密钥错误。

MongoDB Bulk.insert() 方法

此方法以集合数进行插入操作. 它从版本 2.6 开始引入。 语法是 Bulk.insert(<document>). 文档:指定要插入的文档. 现在我们将看到集合插入的例子。

大量无序插入

 1> var carbulk = db.car.initializeUnorderedBulkOp();
 2> carbulk.insert({ name:"Ritz", color:"Grey",cno:"H109",mfdcountry:"Mexico",speed:62});
 3> carbulk.insert({ name:"Versa", color:"Magenta",cno:"H110",mfdcountry:"France",speed:68});
 4> carbulk.insert({ name:"Innova", color:"JetRed",cno:"H111",mfdcountry:"Dubai",speed:72});
 5> carbulk.execute();
 6BulkWriteResult({
 7    "writeErrors" : [ ],
 8    "writeConcernErrors" : [ ],
 9    "nInserted" : 3,
10    "nUpserted" : 0,
11    "nMatched" : 0,
12    "nModified" : 0,
13    "nRemoved" : 0,
14    "upserted" : [ ]
15})
16>

创建一个名为 carbulk 的非排序列表,并指定插入查询与要插入的字段、值。 请注意,需要在最后一个插入陈述后调用 execute() 方法,以确保数据实际上被插入到数据库中。

MongoDB 批量订购插件

这类似于未分配的大量插入,但我们使用initializeOrderedBulkOp呼叫。

 1>var car1bulk = db.car.initializeOrderedBulkOp();
 2>car1bulk.insert({ name:"Ertiga", color:"Red",cno:"H112",mfdcountry:"America",speed:65});
 3>car1bulk.insert({ name:"Quanta", color:"Maroon",cno:"H113",mfdcountry:"Rome",speed:78});
 4>car1bulk.execute();
 5BulkWriteResult({
 6    "writeErrors" : [ ],
 7    "writeConcernErrors" : [ ],
 8    "nInserted" : 2,
 9    "nUpserted" : 0,
10    "nMatched" : 0,
11    "nModified" : 0,
12    "nRemoved" : 0,
13    "upserted" : [ ]
14})

首先,我们创建一个名为 carbulk1 的排序列表,然后通过引用 execute() 方法插入文件。

MongoDB 大量插入Java程序

让我们来看看一个用于不同批量操作的java程序,迄今为止我们已经看到使用壳命令,下面是使用MongoDB java驱动程序版本 2.x的大量插入的java程序。

  1package com.journaldev.mongodb;
  2
  3import com.mongodb.BasicDBObject;
  4import com.mongodb.BulkWriteOperation;
  5import com.mongodb.BulkWriteResult;
  6import com.mongodb.DB;
  7import com.mongodb.DBCollection;
  8import com.mongodb.DBCursor;
  9import com.mongodb.DBObject;
 10import com.mongodb.MongoClient;
 11import java.net.UnknownHostException;
 12import java.util.ArrayList;
 13import java.util.List;
 14
 15public class MongoDBBulkInsert {
 16
 17    //method that inserts all the documents 
 18    public static void insertmultipledocs() throws UnknownHostException{
 19
 20    //Get a new connection to the db assuming that it is running    
 21
 22     MongoClient mongoClient = new MongoClient("localhost");
 23
 24     ////use test as a datbase,use your database here 
 25     DB db=mongoClient.getDB("test");
 26
 27     ////fetch the collection object ,car is used here,use your own 
 28     DBCollection coll = db.getCollection("car");
 29
 30    //create a new object
 31    DBObject d1 = new BasicDBObject();
 32
 33    //data for object d1
 34    d1.put("_id", 11);
 35    d1.put("name","WagonR");
 36    d1.put("color", "MetallicSilver");
 37    d1.put("cno", "H141");
 38    d1.put("mfdcountry","Australia");
 39    d1.put("speed",66);
 40
 41    DBObject d2 = new BasicDBObject();
 42
 43    //data for object d2
 44    d2.put("_id", 12);
 45    d2.put("name","Xylo");
 46    d2.put("color", "JetBlue");
 47    d2.put("cno", "H142");
 48    d2.put("mfdcountry","Europe");
 49    d2.put("speed",69);
 50
 51    DBObject d3 = new BasicDBObject();
 52
 53    //data for object d3
 54    d3.put("_id", 13);
 55    d3.put("name","Alto800");
 56    d3.put("color", "JetGrey");
 57    d3.put("cno", "H143");
 58    d3.put("mfdcountry","Austria");
 59    d3.put("speed",74);
 60
 61    //create a new list
 62    List<DBObject> docs = new ArrayList<>();
 63
 64    //add d1,d2 and d3 to list docs
 65    docs.add(d1);
 66    docs.add(d2);
 67    docs.add(d3);
 68
 69    //insert list docs to collection
 70    coll.insert(docs);
 71
 72    //stores the result in cursor
 73    DBCursor carmuldocs = coll.find();
 74
 75    //print the contents of the cursor
 76     try {
 77         while(carmuldocs.hasNext()) {
 78       System.out.println(carmuldocs.next());
 79        }
 80    }        finally {
 81            carmuldocs.close();//close the cursor
 82    } 
 83
 84    }
 85
 86    //method that inserts documents with some fields
 87    public static void insertsomefieldsformultipledocs() throws UnknownHostException{
 88
 89    //Get a new connection to the db assuming that it is running    
 90
 91     MongoClient mongoClient = new MongoClient("localhost");
 92
 93     ////use test as a datbase,use your database here 
 94     DB db=mongoClient.getDB("test");
 95
 96     ////fetch the collection object ,car is used here,use your own 
 97     DBCollection coll = db.getCollection("car");
 98
 99    //create object d1 
100    DBObject d1 = new BasicDBObject();
101
102    //insert data for name,color and speed
103    d1.put("name","Indica");
104    d1.put("color", "Silver");
105    d1.put("cno", "H154");
106
107    DBObject d2 = new BasicDBObject();
108
109    //insert data for id,name and speed
110    d2.put("_id", 43);
111    d2.put("name","Astar");
112
113    d2.put("speed",79);
114
115    List<DBObject> docs = new ArrayList<>();
116    docs.add(d1);
117    docs.add(d2);
118
119    coll.insert(docs);
120
121    DBCursor carmuldocs = coll.find();
122
123     System.out.println("-----------------------------------------------");
124     try {
125         while(carmuldocs.hasNext()) {
126       System.out.println(carmuldocs.next());
127        }
128    }        finally {
129            carmuldocs.close();//close the cursor
130    } 
131
132    }
133
134    //method that checks for duplicate documents
135    public static void insertduplicatedocs() throws UnknownHostException{
136
137    //Get a new connection to the db assuming that it is running    
138
139     MongoClient mongoClient = new MongoClient("localhost");
140
141     ////use test as a datbase,use your database here 
142     DB db=mongoClient.getDB("test");
143
144     ////fetch the collection object ,car is used here,use your own 
145     DBCollection coll = db.getCollection("car");
146
147    DBObject d1 = new BasicDBObject();
148
149    //insert duplicate data of id11
150    d1.put("_id", 11);
151    d1.put("name","WagonR-Lxi");
152
153    coll.insert(d1);
154
155    DBCursor carmuldocs = coll.find();
156
157     System.out.println("-----------------------------------------------");
158     try {
159         while(carmuldocs.hasNext()) {
160       System.out.println(carmuldocs.next());
161        }
162    }        finally {
163            carmuldocs.close();//close the cursor
164    } 
165
166    }
167
168    //method to perform bulk unordered list
169    public static void insertbulkunordereddocs() throws UnknownHostException{
170
171    //Get a new connection to the db assuming that it is running    
172
173     MongoClient mongoClient = new MongoClient("localhost");
174
175     ////use test as a datbase,use your database here 
176     DB db=mongoClient.getDB("test");
177
178     ////fetch the collection object ,car is used here,use your own 
179     DBCollection coll = db.getCollection("car");
180
181    DBObject d1 = new BasicDBObject();
182
183    d1.put("name","Suzuki S-4");
184    d1.put("color", "Yellow");
185    d1.put("cno", "H167");
186    d1.put("mfdcountry","Italy");
187    d1.put("speed",54);
188
189    DBObject d2 = new BasicDBObject();
190
191    d2.put("name","Santro-Xing");
192    d2.put("color", "Cyan");
193    d2.put("cno", "H164");
194    d2.put("mfdcountry","Holand");
195    d2.put("speed",76);
196
197    //intialize and create a unordered bulk
198    BulkWriteOperation b1 = coll.initializeUnorderedBulkOperation();
199
200    //insert d1 and d2 to bulk b1
201    b1.insert(d1);
202    b1.insert(d2);
203
204    //execute the bulk
205    BulkWriteResult r1 = b1.execute();
206
207    DBCursor carmuldocs = coll.find();
208
209    System.out.println("-----------------------------------------------");
210     try {
211         while(carmuldocs.hasNext()) {
212       System.out.println(carmuldocs.next());
213        }
214    }        finally {
215            carmuldocs.close();//close the cursor
216    } 
217
218    }
219
220    //method that performs bulk insert for ordered list
221       public static void insertbulkordereddocs() throws UnknownHostException{
222
223    //Get a new connection to the db assuming that it is running    
224
225     MongoClient mongoClient = new MongoClient("localhost");
226
227     ////use test as a datbase,use your database here 
228     DB db=mongoClient.getDB("test");
229
230     ////fetch the collection object ,car is used here,use your own 
231     DBCollection coll = db.getCollection("car");
232
233    DBObject d1 = new BasicDBObject();
234
235    d1.put("name","Palio");
236    d1.put("color", "Purple");
237    d1.put("cno", "H183");
238    d1.put("mfdcountry","Venice");
239    d1.put("speed",82);
240
241    DBObject d2 = new BasicDBObject();
242
243    d2.put("name","Micra");
244    d2.put("color", "Lime");
245    d2.put("cno", "H186");
246    d2.put("mfdcountry","Ethopia");
247    d2.put("speed",84);
248
249    //initialize and create ordered bulk 
250    BulkWriteOperation b1 = coll.initializeOrderedBulkOperation();
251
252    b1.insert(d1);
253    b1.insert(d2);
254
255    //invoking execute
256    BulkWriteResult r1 = b1.execute();
257
258    DBCursor carmuldocs = coll.find();
259
260    System.out.println("-----------------------------------");
261
262     try {
263         while(carmuldocs.hasNext()) {
264       System.out.println(carmuldocs.next());
265        }
266    }        finally {
267            carmuldocs.close();//close the cursor
268    } 
269
270    }
271
272    public static void main(String[] args) throws UnknownHostException{
273
274       //invoke all the methods to perform insert operation
275
276       insertmultipledocs();
277       insertsomefieldsformultipledocs();
278
279        insertbulkunordereddocs();
280        insertbulkordereddocs();
281        insertduplicatedocs();
282    }
283
284}

下面是上面的节目结果。

 1{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
 2{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
 3{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
 4-----------------------------------------------
 5{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
 6{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
 7{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
 8{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
 9{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
10-----------------------------------------------
11{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
12{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
13{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
14{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
15{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
16{ "_id" : { "$oid" : "548860e803649b8efac5a1d8"} , "name" : "Suzuki S-4" , "color" : "Yellow" , "cno" : "H167" , "mfdcountry" : "Italy" , "speed" : 54}
17{ "_id" : { "$oid" : "548860e803649b8efac5a1d9"} , "name" : "Santro-Xing" , "color" : "Cyan" , "cno" : "H164" , "mfdcountry" : "Holand" , "speed" : 76}
18-----------------------------------
19{ "_id" : 11 , "name" : "WagonR" , "color" : "MetallicSilver" , "cno" : "H141" , "mfdcountry" : "Australia" , "speed" : 66}
20{ "_id" : 12 , "name" : "Xylo" , "color" : "JetBlue" , "cno" : "H142" , "mfdcountry" : "Europe" , "speed" : 69}
21{ "_id" : 13 , "name" : "Alto800" , "color" : "JetGrey" , "cno" : "H143" , "mfdcountry" : "Austria" , "speed" : 74}
22{ "_id" : { "$oid" : "548860e803649b8efac5a1d7"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
23{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
24{ "_id" : { "$oid" : "548860e803649b8efac5a1d8"} , "name" : "Suzuki S-4" , "color" : "Yellow" , "cno" : "H167" , "mfdcountry" : "Italy" , "speed" : 54}
25{ "_id" : { "$oid" : "548860e803649b8efac5a1d9"} , "name" : "Santro-Xing" , "color" : "Cyan" , "cno" : "H164" , "mfdcountry" : "Holand" , "speed" : 76}
26{ "_id" : { "$oid" : "548860e803649b8efac5a1da"} , "name" : "Palio" , "color" : "Purple" , "cno" : "H183" , "mfdcountry" : "Venice" , "speed" : 82}
27{ "_id" : { "$oid" : "548860e803649b8efac5a1db"} , "name" : "Micra" , "color" : "Lime" , "cno" : "H186" , "mfdcountry" : "Ethopia" , "speed" : 84}
28Exception 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}
29    at com.mongodb.CommandResult.getWriteException(CommandResult.java:88)
30    at com.mongodb.CommandResult.getException(CommandResult.java:79)
31    at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:314)
32    at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:189)
33    at com.mongodb.DBCollectionImpl.insert(DBCollectionImpl.java:165)
34    at com.mongodb.DBCollection.insert(DBCollection.java:93)
35    at com.mongodb.DBCollection.insert(DBCollection.java:78)
36    at com.mongodb.DBCollection.insert(DBCollection.java:120)
37    at com.journaldev.mongodb.MongoDBBulkInsert.insertduplicatedocs(MongoDBBulkInsert.java:163)
38    at com.journaldev.mongodb.MongoDBBulkInsert.main(MongoDBBulkInsert.java:304)

如果您正在使用 MongoDB java 驱动程序 3.x,请使用下面的程序。

  1package com.journaldev.mongodb.main;
  2
  3import java.net.UnknownHostException;
  4import java.util.ArrayList;
  5import java.util.List;
  6
  7import org.bson.Document;
  8
  9import com.mongodb.MongoClient;
 10import com.mongodb.client.FindIterable;
 11import com.mongodb.client.MongoCollection;
 12import com.mongodb.client.MongoDatabase;
 13
 14public class MongoDBBulkInsert {
 15
 16    public static void main(String[] args) throws UnknownHostException {
 17
 18    	// invoke all the methods to perform insert operation
 19
 20    	insertmultipledocs();
 21    	insertsomefieldsformultipledocs();
 22
 23    	insertduplicatedocs();
 24    }
 25
 26    // method that inserts all the documents
 27    public static void insertmultipledocs() throws UnknownHostException {
 28
 29    	// Get a new connection to the db assuming that it is running
 30
 31    	MongoClient mongoClient = new MongoClient("localhost");
 32
 33    	//// use test as a database,use your database here
 34    	MongoDatabase db = mongoClient.getDatabase("test");
 35
 36    	//// fetch the collection object ,car is used here,use your own
 37    	MongoCollection<Document> coll = db.getCollection("car");
 38
 39    	// create a new object
 40    	Document d1 = new Document();
 41
 42    	// data for object d1
 43    	d1.put("_id", 11);
 44    	d1.put("name", "WagonR");
 45    	d1.put("color", "MetallicSilver");
 46    	d1.put("cno", "H141");
 47    	d1.put("mfdcountry", "Australia");
 48    	d1.put("speed", 66);
 49
 50    	Document d2 = new Document();
 51
 52    	// data for object d2
 53    	d2.put("_id", 12);
 54    	d2.put("name", "Xylo");
 55    	d2.put("color", "JetBlue");
 56    	d2.put("cno", "H142");
 57    	d2.put("mfdcountry", "Europe");
 58    	d2.put("speed", 69);
 59
 60    	Document d3 = new Document();
 61
 62    	// data for object d3
 63    	d3.put("_id", 13);
 64    	d3.put("name", "Alto800");
 65    	d3.put("color", "JetGrey");
 66    	d3.put("cno", "H143");
 67    	d3.put("mfdcountry", "Austria");
 68    	d3.put("speed", 74);
 69
 70    	// create a new list
 71    	List<Document> docs = new ArrayList<>();
 72
 73    	// add d1,d2 and d3 to list docs
 74    	docs.add(d1);
 75    	docs.add(d2);
 76    	docs.add(d3);
 77
 78    	// insert list docs to collection
 79    	coll.insertMany(docs);
 80
 81    	// stores the result in cursor
 82    	FindIterable<Document> carmuldocs = coll.find();
 83
 84    	for (Document d : carmuldocs)
 85    		System.out.println(d);
 86
 87    	mongoClient.close();
 88    }
 89
 90    // method that inserts documents with some fields
 91    public static void insertsomefieldsformultipledocs() throws UnknownHostException {
 92
 93    	// Get a new connection to the db assuming that it is running
 94
 95    	MongoClient mongoClient = new MongoClient("localhost");
 96
 97    	//// use test as a datbase,use your database here
 98    	MongoDatabase db = mongoClient.getDatabase("test");
 99
100    	//// fetch the collection object ,car is used here,use your own
101    	MongoCollection<Document> coll = db.getCollection("car");
102
103    	// create object d1
104    	Document d1 = new Document();
105
106    	// insert data for name,color and speed
107    	d1.put("name", "Indica");
108    	d1.put("color", "Silver");
109    	d1.put("cno", "H154");
110
111    	Document d2 = new Document();
112
113    	// insert data for id,name and speed
114    	d2.put("_id", 43);
115    	d2.put("name", "Astar");
116
117    	d2.put("speed", 79);
118
119    	List<Document> docs = new ArrayList<>();
120    	docs.add(d1);
121    	docs.add(d2);
122
123    	coll.insertMany(docs);
124
125    	FindIterable<Document> carmuldocs = coll.find();
126
127    	System.out.println("-----------------------------------------------");
128
129    	for (Document d : carmuldocs)
130    		System.out.println(d);
131
132    	mongoClient.close();
133
134    }
135
136    // method that checks for duplicate documents
137    public static void insertduplicatedocs() throws UnknownHostException {
138
139    	// Get a new connection to the db assuming that it is running
140
141    	MongoClient mongoClient = new MongoClient("localhost");
142
143    	//// use test as a database, use your database here
144    	MongoDatabase db = mongoClient.getDatabase("test");
145
146    	//// fetch the collection object ,car is used here,use your own
147    	MongoCollection<Document> coll = db.getCollection("car");
148
149    	Document d1 = new Document();
150
151    	// insert duplicate data of id11
152    	d1.put("_id", 11);
153    	d1.put("name", "WagonR-Lxi");
154
155    	coll.insertOne(d1);
156
157    	FindIterable<Document> carmuldocs = coll.find();
158
159    	System.out.println("-----------------------------------------------");
160
161    	for (Document d : carmuldocs)
162    		System.out.println(d);
163
164    	mongoClient.close();
165
166    }
167
168}

Below image shows sample run of above mongodb bulk insert java program. MongoDB bulk insert, mongodb insertMany That's all for bulk insert in MongoDB using Mongo shell and java driver, we will look into more MongoDB operations in coming posts.

Published At
Categories with 技术
Tagged with
comments powered by Disqus