java mongodb upsert() 方法

╰半夏微凉° 2023-01-22 13:55 74阅读 0赞

需求:通过mongodb的批量操作,对数据进行保存或者修改;
如果数据在mongodb不存在就保存数据,如果数据存在,就修改数据;

  1. String collectionName = "collectionName";
  2. // 这了是数据来源
  3. JSONArray array = messageStatus.getJsonObject().getJSONArray("objs");
  4. if (array != null && array.size() > 0) {
  5. //mongo的批量操作
  6. BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
  7. for (int i = 0; i < array.size(); i++) {
  8. JSONObject json = array.getJSONObject(i);
  9. String id = json.getString("id");
  10. String tid = json.getString("tid");
  11. // 这里是查询语句
  12. Query query = new Query(Criteria.where("tid").is(tid).and("id").is(id));
  13. Document doc = Document.parse(json.toJSONString());
  14. Update update = Update.fromDocument(doc);
  15. update.currentDate("lastModified");
  16. // 这里先根据查询找,有就插入,没有就修改
  17. operations.upsert(query, update);
  18. }
  19. // 批量执行
  20. operations.execute();
  21. }

问题:根据tid与id在mongodb能找到数据,但是通过mongodb的upsert方法操作之后,一直在插入数据,而不是修改数据;

  1. Query query = new Query(Criteria.where("tid").is(tid).and("id").is(id));
  2. mongoTemplate.find(query,JSONObject.class,"collectionName");
  3. 能查到数据

通过比对数据类型,发现:我查询是使用的tid与id使用了String类型,而mongodb中保存的是int类型,这样造成的不完整匹配,所以一直插入,而不是修改;
在这里插入图片描述
解决:
将我的查询语句改成了Integer或Long类型就好了

  1. 。。。
  2. Integer id = json.getInteger("id");
  3. Integer tid = json.getInteger("tid");
  4. 。。。

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读

    相关 MongoDB安装方法

    MongoDB 下载 MongoDB 提供了可用于 32 位和 64 位系统的预编译二进制包,你可以从MongoDB官网下载安装,MongoDB 预编译二进制包下载地址: