如何在Spring Boot Mongodb中进行自定义高级搜索

时间:2019-04-30 09:51:25

标签: java spring spring-boot spring-data-mongodb mongorepository

我的目标是使用Spring Boot和Mongodb进行自定义高级搜索。

控制器类:

@Autowired
UserService userService;

@RequestMapping(value = "/users", method = GET)
public ResponseEntity<List<User>> getUsersByType(@RequestParam("type") String type, 
@RequestParam("id") String id) throws ParseException {

    List<User> usersList = userService.getUsersByType(type, id);
    return new ResponseEntity<List<User>>(partnerList, HttpStatus.OK);
}

服务类别:

@Service
public class UserService {

@Autowired
UserRepository userRepository;

public List<User> getUsersByType(String type, String id){
    return  userRepository.findBySignUp(type,id);
}

}

存储库类:

@RepositoryRestResource(collectionResourceRel = "user",path = "user")
public interface UserRepository extends MongoRepository<User,String> {

 List<User> findBySignUp(String signUpType, String id);

}

但是在这种情况下,我想传递两个参数并根据以下mongo收集模式进行高级搜索:

用户集合:

{  
 "_id":ObjectId("5cad672e902bb3438441bd9d"),
 "email":"user.example@gmail.com",
 "name":"User1",
 "bookletSignUps":[  
  DBRef("booklet",ObjectId("5cad672e902bb3438441bd9c")),
  DBRef("booklet",ObjectId("5cad6747902bb3438441bd9e")),
  DBRef("booklet",ObjectId("5cad6a28902bb346a792c5d3"))
 ],
 "eventSignUps":[  
  DBRef("event",ObjectId("5cad69e5902bb346a792c5d0")),
  DBRef("event",ObjectId("5cad69ff902bb346a792c5d1"))
 ],
  "businessName":"Sample",
  "phone":"test phone number",
  "address":"test address",
  "createdTime":"2015-09-26T01:30:00.000Z",
  "updatedTime":"2017-09-26T01:30:00.000Z"
 }

用户模型类:

@Document(collection = "user")
public class User {

@Id
private String id;
private String email;
private String name;
private String businessName;
private String phone;
private String address;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date createdTime;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date updatedTime;
@Field("bookletSignups")
@DBRef
private BookletSignUp bookletSignups;
@Field("eventSignups")
@DBRef
private EventSignUp eventSignups;
@Field("infoSignups")
@DBRef
private InfoSignUp infoSignups;
@Field("webinarSignups")
@DBRef
private WebinarSignUp webinarSignups;

}

因此,基于此,我想过滤具有特定signUpType和相应的signUpId的用户。 因此,如果signUpType为bookletSignUps且ID为5cad672e902bb3438441bd9c,我想过滤出ID为bookletSignUps的{​​{1}}记录的用户 如何在MongoRepository中进行搜索?我对mongo有点新手,因此支持的想法将不胜感激。预先感谢。

0 个答案:

没有答案