mongodb支持批量插入。

1.使用Java mongodb api

查看源码com.mongodb.MongoCollectionImpl,有两个方法

@Override
public void insertMany(final List<? extends TDocument> documents) {
insertMany(documents, new InsertManyOptions());
} @Override
public void insertMany(final List<? extends TDocument> documents, final InsertManyOptions options) {
notNull("documents", documents);
List<InsertRequest> requests = new ArrayList<InsertRequest>(documents.size());
for (TDocument document : documents) {
if (document == null) {
throw new IllegalArgumentException("documents can not contain a null value");
}
if (getCodec() instanceof CollectibleCodec) {
document = ((CollectibleCodec<TDocument>) getCodec()).generateIdIfAbsentFromDocument(document);
}
requests.add(new InsertRequest(documentToBsonDocument(document)));
}
executor.execute(new MixedBulkWriteOperation(namespace, requests, options.isOrdered(), writeConcern)
.bypassDocumentValidation(options.getBypassDocumentValidation()));
}
insertMany(final List<? extends TDocument> documents) 默认使用 private boolean ordered = true;即有序插入。
insertMany(final List<? extends TDocument> documents, final InsertManyOptions options)调用者自己设置。

ordered属性有什么用?
 /**
* Gets whether the documents should be inserted in the order provided, stopping on the first failed insertion. The default is true.
* If false, the server will attempt to insert all the documents regardless of an failures.
*
* @return whether the the documents should be inserted in order
*/
public boolean isOrdered() {
return ordered;
}

大概意思是:

true:按提供的顺序插入文档,并在首次插入失败时停止。 (按顺序插入文档,遇到失败后停止。之前已经插入成功的不返回,失败及失败之后的不插入。)

false: 服务器将尝试插入所有文档,而不考虑失败。(只要能插入成功的,都存储进数据库)

2.spring-data-mongodb

org.springframework.data.mongodb.core.MongoTemplate

以下是该方法的源码和使用案例:

    /*
* (non-Javadoc)
* @see org.springframework.data.mongodb.core.ExecutableInsertOperation#bulkOps(org.springframework.data.mongodb.core.BulkMode, java.lang.String)
*/
public BulkOperations bulkOps(BulkMode bulkMode, String collectionName) {
return bulkOps(bulkMode, null, collectionName);
}
public int batchInsertStudents() {
      BulkWriteResult result = null;
      try {
  List<Student> documents = new ArrayList<>();
  String collectionName = "myTestCol";
  BulkOperations bulkOp = this.mongoTemplate.bulkOps(BulkMode.UNORDERED, collectionName);
  for(int i = 502610; i< 2000000; i++) {
  Student student = new Student();
  student.setId(String.valueOf(i));
  student.setAge(i);
  student.setGender("男");
  student.setName("李三"+ i);
  documents.add(student);
  }
  bulkOp.insert(documents);
result = bulkOp.execute();
}catch (DuplicateKeyException e) {
System.out.println("**********" + e.getMessage());
 }
return result;
}

有两种模式:

    /**
* Mode for bulk operation.
**/
enum BulkMode { /** Perform bulk operations in sequence. The first error will cancel processing. */
ORDERED, /** Perform bulk operations in parallel. Processing will continue on errors. */
UNORDERED
};

与之前的order(true|false)相对应。

mongodb批量处理的更多相关文章

  1. MongoDB批量导入及简单的性能优化

    今天简单分享一下MongoDB使用过程中的一些性能优化,其实并不只适用MongoDB,其他数据库多少也可适用. 首先先随机导入一千万条数据.这里我分段导入的,因为mongo的BsonDocument一 ...

  2. mongodb批量插入数据

    年前由于公司业务需要,后台需要获取流水记录,需要每天定时跑脚本,将流水记录跑入库里边,每天大概有个一百万左右,使用的数据库是mongodb,考虑到一条一条录入数据,100多万会跑断,就想着批量录入数据 ...

  3. mongodb 批量更新 数组的键操作的文件

    persons该文件的数据如下面的: > db.persons.find() { "_id" : 2, "name" : 2 } { "_id& ...

  4. mongodb批量更新操作文档的数组键

    persons文档的数据如下: > db.persons.find(){ "_id" : 2, "name" : 2 }{ "_id" ...

  5. MongoDB批量更新和批量插入的方式

    最近,在调试代码中发现向MongoDB插入或者更新文档记录时若是多条的话都是采用for循环操作的,这样的处理方式会造成数据操作耗时,不符合批量处理的原则:对此,个人整理了一下有关MongoDB的批量更 ...

  6. mongoDB 批量更改数据,某个字段值等于另一个字段值

    由于mongodb数据库类似js的写法,所以即使数据库中新的列不存在也会自动创建 db.hospital.find().forEach( function(item){ db.hospital.upd ...

  7. Django+MongoDB批量插入数据

    在百万级和千万级数据级别进行插入,pymongo的insert_many()方法有着很强的优势.原因是每次使用insert_one()方法进行插入数据,都是要对数据库服务器进行一次访问,而这样的访问是 ...

  8. 亿级别记录的mongodb批量导入Es的java代码完整实现

    针对mongodb亿级别或者十亿级别的模糊查询,效率不高,解决方式是使用Es查询,这样就需要把数据导入的ES中 完整的代码实现如下所示:(仅供参考) import java.io.IOExceptio ...

  9. mongodb 批量添加、修改和删除

    1.使用MongoTemplate a.批量插入 Insert a Collection of objects into a collection in a single batch write to ...

随机推荐

  1. PAT B1014/A1061 福尔摩斯的约会(20)

    书中AC代码 #include <cstdio> #include <iostream> #include <cstring> using namespace st ...

  2. POJ - 3687 Labeling Balls (拓扑)

    (点击此处查看原题) 题意 此处有n盏灯,编号为1~n,每盏灯的亮度都是唯一的,且在1~n范围之间,现已知m对灯之间的关系:a b ,说明灯a的亮度比灯b小,求出每盏灯的亮度,要求字典序最小(编号小的 ...

  3. selenium的使用与chromedriver的下载配置

    Selenium是一个web自动化测试工具,最初是为网站自动化测试而开发的,Selenium可以直接运行在浏览器上,它支持所有主流的浏览器,可以接受指令,让浏览器自动加载页面,获得需要的数据,甚至页面 ...

  4. C - 简易贪吃蛇的编写

    不多废话,直接进入正题——用C编写简易贪吃蛇.附上拙劣的源码 * c-snake * 首先说明使画面动起来的原理:通过 system("cls"); 清除当前控制台的显示,再pri ...

  5. redis 学习(18)-- AOF

    redis -- AOF 什么是 AOF 通过日志方式将redis中的写命令进行日志记录,保存在硬盘文件中. 日志记录的实质是将写命令写在硬盘的缓冲区中,再根据相关策略把数据刷新到磁盘中. 当redi ...

  6. Struts框架的使用初步

    Struts框架的使用初步: A:Apache下载struts.2.1.8.rar包. B:解压空工程,进入apps目录. C:将struts2的基本jar包拷到工程的lib目录中. D:配置web. ...

  7. WAV格式文件无损合并&帧头数据体解析(python)(原创)

    一,百度百科 WAV为微软公司(Microsoft)开发的一种声音文件格式,它符合RIFF(Resource Interchange File Format)文件规范,用于保存Windows平台的音频 ...

  8. asp.net 7.分页

    分页 SQL: select * from( select *,row_number()over(order by id) as num from T_userInfo) as t 数据层(UserI ...

  9. windows server12 FTP 创建后常见问题

    一:用administrator 关闭防火墙可以访问,但是开启后不能访问 今天在windows server 2008 R2上安装了FTP,安装过程如下,然后添加内置防火墙设置,设置后发现本地可以访问 ...

  10. PMP - 风险识别之风险登记册

    目录 PMP - 风险识别之风险登记册 1. 风险登记册 1.1 已识别风险的清单 1.2 潜在风险责任人 1.3 潜在风险应对措施清单 2. 相关习题 2.1 风险发生的时候,要实施 风险登记册 上 ...