java mongodb upsert() 方法
需求:通过mongodb的批量操作,对数据进行保存或者修改;
如果数据在mongodb不存在就保存数据,如果数据存在,就修改数据;
String collectionName = "collectionName";
// 这了是数据来源
JSONArray array = messageStatus.getJsonObject().getJSONArray("objs");
if (array != null && array.size() > 0) {
//mongo的批量操作
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, collectionName);
for (int i = 0; i < array.size(); i++) {
JSONObject json = array.getJSONObject(i);
String id = json.getString("id");
String tid = json.getString("tid");
// 这里是查询语句
Query query = new Query(Criteria.where("tid").is(tid).and("id").is(id));
Document doc = Document.parse(json.toJSONString());
Update update = Update.fromDocument(doc);
update.currentDate("lastModified");
// 这里先根据查询找,有就插入,没有就修改
operations.upsert(query, update);
}
// 批量执行
operations.execute();
}
问题:根据tid与id在mongodb能找到数据,但是通过mongodb的upsert方法操作之后,一直在插入数据,而不是修改数据;
Query query = new Query(Criteria.where("tid").is(tid).and("id").is(id));
mongoTemplate.find(query,JSONObject.class,"collectionName");
能查到数据
通过比对数据类型,发现:我查询是使用的tid与id使用了String类型,而mongodb中保存的是int类型,这样造成的不完整匹配,所以一直插入,而不是修改;
解决:
将我的查询语句改成了Integer或Long类型就好了
。。。
Integer id = json.getInteger("id");
Integer tid = json.getInteger("tid");
。。。
还没有评论,来说两句吧...