usering mongotemplate bases on spring-Data-mongo

东北大亨發表於2024-03-15

1、find

  • mongoTemplate.find(Query query, Class<T> entityClass )
    • return value : List<T>
    • example: List<users> users = mongoTemplate.find(new Query(Criteria.where("age").is(20).and("name").is("zhangsan")), users.class);
    • List<users> users = mongoTemplate.find(new Query(Criteria.where("age").is(20).and("name").is("northeasttycoon")), BasicDBObject.class);
  • mongoTemplate.find(Query query, Class<T> entityClass,String Collectionname )
    • result: List<T>
    • example: List<users> users1 = mongoTemplate.find(new Query(Criteria.where("age").is(20).and("name").is("northeasttycoon")), users.class, "uses");
  • mongoTemplate.findAll(Class<T> entityClass)
    • result: List<T>
    • example: List<users> userList= mongoTemplate.findAll(users.class);
  • code example:

// query all data

List<users> usersList = mongoTemplate.findAll(users.class);

// query users collection base on condition

List<users> users = mongoTemplate.find(new Query(Criteria.where("age").is(20).and("name").is("zhangsan")), users.class);

2、Aggregation

  • Aggregation.project(String... fields)
    • result: ProjectionOperation
    • example : ProjectionOperation project = Aggregation.project("age", "name");
  • Aggregation.match(Criteria criteria)
    • result::MatchOperation
    • example: MatchOperation match = Aggregation.match( Criteria().where("age").is(20));
  • Aggregation.group(String... fields )
    • result: GroupOperation
    • example: GroupOperation group = Aggregation.group("username","age").sum("age").as("count");