public <T> T selectMongoTopOne(Integer f1, String f2, String f3, Class<T> clazz) {
Criteria[] arr = new Criteria[3];
arr[0] = Criteria.where("field1").is(f1);
arr[1] = Criteria.where("field2").is(f2);
arr[2] = Criteria.where("field3").is(f3);
Criteria criteria = new Criteria().andOperator(arr);
Query query = new Query(criteria);
query.with(Sort.by(Sort.Order.desc("createdTime"))).limit(1);
return mongoTemplate.findOne(query, clazz);
}
提示:clazz为对应的mongo文档集合类
private <T> void mongoUpdatePush(Integer f1, String f2, String updateKey, Object UpdateValue, Class<T> tClass) {
Query query = new Query();
query.addCriteria(Criteria.where("field1").is(f1).and("field2").is(f2));
Update update = new Update();
update.set(updateKey, UpdateValue);
UpdateResult updateResult = mongoTemplate.updateFirst(query, update, tClass);
log.info("查询mongo数据匹配{}条记录,修改了{}条记录", updateResult.getMatchedCount(), updateResult.getModifiedCount());
提示:tClass为对应的mongo文档集合类
private <T> void mongoUpdatePush(Integer f1, String f2, String updateKey, Object UpdateValue, Class<T> tClass) {
Query query = new Query();
query.addCriteria(Criteria.where("field1").is(f1).and("field2").is(f2));
Update update = new Update().addToSet(updateKey, UpdateValue);
mongoTemplate.updateFirst(query, update, tClass);
}
提示:tClass为对应的mongo文档集合类
private void mongoUpdateSet(Integer f1, String f2, String dataName, BasicDBObject update) {
// 修改arrays数组下的某条记录dataUid变量值为test
BasicBSONObject eleSetBson = new BasicBSONObject();
eleSetBson.put("arrays.$[arrays].dataUid", "test");
BasicDBObject update = new BasicDBObject();
update.put("$set", eleSetBson);
// 查询对应唯一集合
Criteria criteria = Criteria.where("field1").is(f1).and("field2").is(f2);
// 拼接数组过滤filter参数-updateOptions
UpdateOptions updateOptions = new UpdateOptions();
List list = new ArrayList();
BasicDBObject eleFilterBson = new BasicDBObject();
eleFilterBson.put("arrays.dataName", dataName);
list.add(eleFilterBson);
updateOptions.arrayFilters(list);
mongoTemplate.getCollection("t_datas").updateOne(
criteria.getCriteriaObject(),
update,
updateOptions
);
}
提示:array.dataName中array为数组变量名称,dataName为数组中的具体某个变量名,t_datas为对应的mongo文档集合名称。arrays.$[arrays].dataUid中的dataUid为数组下的具体某个变量名
参考文章:
https://blog.csdn.net/weixin_42260311/article/details/115634232
https://blog.csdn.net/maying0124/article/details/120214034
https://www.codercto.com/a/64352.html