Java操作Mongo bulkWrite批量入库

it2025-10-18  6

Mongo bulkWrite示例

public boolean insertBulk(String collectionName, JSONArray array) { MongoCollection<Document> collection = db.getCollection(collectionName); List<InsertOneModel<Document>> documentList = array.stream().map(item -> { Document document = Document.parse(((JSONObject)item).toJSONString()); document.put("_id", document.getString("id")); return new InsertOneModel<Document>(document); }).collect(Collectors.toList()); ListUtils.partition(documentList,1000).forEach(item->{ collection.bulkWrite(item); }); return true; }

ListUtils.partition来自于

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.3</version> </dependency>
最新回复(0)