List list = Arrays.asList(
new Employee(3,"小红",20,200.50,new Date()),
new Employee(4,"小李",18,250.50,new Date()),
new Employee(5,"小杨",17,300.00,new Date()),
new Employee(6,"小王",15,100.00,new Date())
);
//Employee employee = new Employee(2,"小张",25,500.00,new Date());
Collection insert = mongoTemplate.insert(list, Employee.class);
//查询薪资大于8000的员工
Query query = new Query(Criteria.where("salary").gte(8000));
List employees = mongoTemplate.find(query, Employee.class);
//查询薪资大于8000小于10000的员工
Query query = new Query(Criteria.where("salary").gte(8000).lte(10000));
List employees = mongoTemplate.find(query, Employee.class);
//模糊查询->查询姓名包含“张”的员工,有其他的需求直接写正则表达式即可
Query query = new Query(Criteria.where("name").regex("张"));
List employees = mongoTemplate.find(query, Employee.class);
//and or
Criteria criteria = new Criteria();
//查询年龄大于20岁且工资低于8000的员工
criteria.andOperator(Criteria.where("name").lt(20),
Criteria.where("salasy").lt(8000));
Query query = new Query(criteria);
List employees = mongoTemplate.find(query, Employee.class);
//and or
Criteria criteria = new Criteria();
//查询年龄大于20岁且工资低于8000的员工
criteria.andOperator(Criteria.where("name").lt(20),
Criteria.where("salary").lt(8000));
Query query = new Query(criteria);
//sort 排序(对薪资进行降序)
query.with(Sort.by(Sort.Order.desc("salary")));
List employees = mongoTemplate.find(query, Employee.class);
//and or
Criteria criteria = new Criteria();
//查询年龄大于20岁且工资低于8000的员工
criteria.andOperator(Criteria.where("name").lt(20),
Criteria.where("salary").lt(8000));
Query query = new Query(criteria);
//sort 排序(对薪资进行降序)
query.with(Sort.by(Sort.Order.desc("salary")));
//分页查询
query.skip(0);//从第0条开始
query.limit(4);//每页返回4条数据
List employees = mongoTemplate.find(query, Employee.class);
String json = "{name:'张三'}";
Query jsonQuery = new BasicQuery(json);
List empList = mongoTemplate.find(query, Employee.class);
Query query = new Query(Criteria.where("cid").is(id).and("is_deleted").is(false));
Update update = new Update();
update.set("is_deleted",true);
mongoTemplate.updateMulti(query,update, Resource.class);
//删除工资高于8000的员工
Query removeQuery = new Query(Criteria.where("salary").gt(8000));
DeleteResult remove = mongoTemplate.remove(new Query(), Employee.class);
db.emp.estimatedDocumentCount():统计:忽略过滤条件
db.emp.distinct():去重
(1):投影操作(取别名),将原始字段名投影成指定名称,如将集合中的name投影成noname -> db.emp.aggregate([$project:{noname:"$name"}])
(2)$project可以灵活的控制输出的格式,也可以剔除不需要的字段->db.emp.aggregate([$project:{noname:"$name",_id:0,age:1}]):0不展示,1展示
(3)从嵌套文档中排除字段(type字段是一个集合,age为集合里面的一个字段) ->
db.emp.aggregate([$project:{noname:"$name",_id:0,"type.age":1}])
或者
db.emp.aggregate([$project:{noname:"$name",_id:0,type:{age:1}}])
实际上就是精准匹配->查询age等于30的->
age_count:返回的结果名称
统计每个作者的每本book的收藏数 每个作者的book的type合集