参考:https://blog.csdn.net/xyy1028/article/details/86468969
Map data = new HashMap();
data.put("name","xiaoge");
data.put("sex","male");
String date = String.format("%1$tF %1$tT", new Date());
data.put("date",date);
mongoTemplate.insert(data,"why");
2.1 排序
Query query=new Query();
query.with(new Sort(Sort.Direction.ASC, "age"));
List users=mongoTemplate.find(query, User.class);
2.2 精确查询
Query query = new Query();
query.addCriteria(Criteria.where("sex").is("male"));
2.3 模糊查询
Pattern pattern=Pattern.compile("^.*"+dateTime+".*$", Pattern.CASE_INSENSITIVE);
Query query = new Query();
query.addCriteria(Criteria.where("date").regex(pattern));
2.4 范围查询
//gte : >= ; lte : <= ; gt : > ; lt : <
Query query = new Query();
query.addCriteria(Criteria.where("date").gt("2019-01-11 14:05:01").lte("2019-01-11 14:09:53"));
List
2.5 分页 limit(size) skip(skipsize)
size:每页几条数据 ; skipsize: 跳过的数据条数
例如:每页size条数据.则第page页的数据为 query.limit(size).skip(size*(page-1))
Query query = new Query();
query.limit(3).skip(3*(4-1));
2.6 综合查询
Query query = new Query();
query.with(new Sort(Sort.Direction.ASC,"date"));
Pattern pattern=Pattern.compile("^.*"+"y"+".*$", Pattern.CASE_INSENSITIVE);
query.addCriteria(Criteria.where("sex").is("male").and("name").regex(pattern).
and("date").gt("2019-01-11 14:05:01").lte("2019-01-11 14:09:53"));
List
2.7 find查询返回指定的字段值
queryBuilder.or() 是条件查询,是查询name=Eric or name=Arriy
fieldsObject.put(key, value) key表示要返回的字段,key为1就是要返回这个字段,其它的字段的值返回都是空,其中_id 这个字段都回返回,除非特定设置了fieldsObject.put("_id", 0),这就不会返回了
QueryBuilder queryBuilder = new QuerBuilder();
queryBuilder.or(new BasicDBObject("name","Eric"),new BasicDBObject("name","Arriy"));
BasicDbObject fieldsObject = new BasicDBObject();
fieldsObject.put("name",1);
fieldsObject.put("age",1);
Query query=new BasicQuery(queryBuilder.get(), fieldsObject);
List list=mongoTemplate.find(query, User.class);
返回几个特定的字段的另外一种写法
Query query=new Query(Criteria.where("tel").is(param));
query.fields().include("person.name").include("like");
mongoTemplate.find(query, Dhh.class);
2.8 多个条件组合查询
例如:查询name=Eric and age=27
Query query=new Query();
query.addCriteria(Criteria.where("name").is("Eric").and("age").is("27")));
List list=mongoTemplate.find(query,User.class);
例如:查询name=Eric or name=Arriy
Query query=new Query();
query.addCriteria(new Criteria.orOperator(Criteria.where("name").is("Eric"),Criteria.where("name").is("Arriy")));
List list=mongoTemplate.find(query,User.class);
2.9 单条查询
findOne()
Map data = mongoTemplate.findOne(query,Map.class,"why");
Query query=new Query(Criteria.where("date").is("2019-01-11 14:14:05"));
long count = mongoTemplate.remove(query,Map.class,"why").getDeletedCount();
https://www.jianshu.com/p/dd7b5a0e2f64
Query query=new Query(Criteria.where("date").is("2019-01-11 14:13:38"));
Update update = Update.update("name","hhd").set("sex","animal");
mongoTemplate.updateFirst(query, update, Map.class,"why");