1.引言
mongoTemplate提供了许多的方法,许多的类似的方法,刚开始不知道使用哪一种最好,现在,我把他们整理如下,方便大家选择使用。
2.常用方法
public void mongoTemplateSample(FormDataApproval formDataApproval) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(formDataApproval.getId()).and("tenant_id").is(formDataApproval.getTenantId()));
Update update = new Update();
update.set("process_id", formDataApproval.getProcessId());
List<FormDataApproval> list = new ArrayList<>();
list.add(formDataApproval);
mongoTemplate.upsert(query, update, FormData.class, "formData");
// 无实际意义,不推荐使用
mongoTemplate.update(FormDataApproval.class);
mongoTemplate.updateFirst(query, update, FormDataApproval.class, "formDataApproval");
mongoTemplate.updateMulti(query, update, FormDataApproval.class, "formDataApproval");
mongoTemplate.findAndModify(query, update, FormDataApproval.class, "formDataApproval");
mongoTemplate.find(query, FormDataApproval.class, "formDataApproval");
mongoTemplate.findOne(query, FormDataApproval.class, "formDataApproval");
mongoTemplate.findAll(FormDataApproval.class, "formDataApproval");
mongoTemplate.findById(formDataApproval.getId(), FormDataApproval.class, "formDataApproval");
mongoTemplate.remove(query, FormDataApproval.class, "formDataApproval");
mongoTemplate.findAndRemove(query, FormDataApproval.class, "formDataApproval");
mongoTemplate.findAllAndRemove(query, FormDataApproval.class, "formDataApproval");
mongoTemplate.save(formDataApproval, "formDataApproval"); // 同upsert(),没有新增,有修改
mongoTemplate.insert(formDataApproval, "formDataApproval");
mongoTemplate.insertAll(list);
}
3.批量修改
@Override
public void updateFormDatas(List<FormData> formDataList) {
if (CollectionUtils.isEmpty(formDataList)) {
return;
}
BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Const.COLLECTION_FORM_DATA);
List<Pair<Query, Update>> list = new ArrayList<>();
for (FormData formData : formDataList) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(formData.getId()).and("tenant_id").is(formData.getTenantId()));
Update update = new Update();
update = mongoUtil.getUpdateFormDataAll(formData, update);
Pair<Query, Update> pair = Pair.of(query, update);
list.add(pair);
}
operations.updateMulti(list);
operations.execute();
}
4.其他方法
public void mongoTempalteAsOriginal() {
// 查询该集合中的所有文档
MongoCollection<Document> formDataApprovalDocument = mongoTemplate.getCollection("formDataApproval");
// 新增
formDataApprovalDocument.insertOne();
formDataApprovalDocument.insertMany();
// 删除
formDataApprovalDocument.deleteOne();
formDataApprovalDocument.deleteMany();
formDataApprovalDocument.findOneAndDelete();
// 修改
formDataApprovalDocument.updateOne();
formDataApprovalDocument.updateMany();
formDataApprovalDocument.findOneAndUpdate();
formDataApprovalDocument.replaceOne();
formDataApprovalDocument.findOneAndReplace();
// 查询
formDataApprovalDocument.find();
// 获取集合name
mongoTemplate.getCollectionName(FormDataApproval.class);
}