繁体   English   中英

使用Spring MongoRepository根据相同查询参数的值的不同组合获取所有Mongo文档

[英]Fetching all Mongo documents based on different combinations of values of same query parameters using Spring MongoRepository

我正在编写一个Web服务,需要在其中响应用户的REST请求提供MongoDb中的文档列表。 过滤器参数在请求的请求有效负载中提供。 我需要使用与参数组合匹配的Spring的MongoRepository接口来获取所有文档。 将以下查询直接应用到集合中将以我想要的方式工作:

db.getCollection('userCollection').find({ '$and' : [ { 'admin':'admin1', 'address':'add1'}, {'$or': [{ 'name' : { '$in':['Amy','Maya'] } }, {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]} ]})

因此,我需要执行以下操作:

  1. 所有文档必须具有“ admin” =“ admin1”和“ address” =“ add1”
  2. 文件必须以[名称]作为[“ Amy”,“ Maya”]之一,或者必须具有以下学校,学院,公司组合之一-

    {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}

这些值和此类组合的数量可能会基于动态出现的Web请求中提供的内容而有所不同。

第二点是我在使用@Query批注将其合并到Java中基于JSON的查询时遇到了麻烦。

我想提供此信息作为以下存储库方法的一部分:

@Query({'$and': [{'admin': ?0, 'address': ?1}, {'$or': [{'name': {'$in': ?2}}, <add solution here for adding list of school-college-company combinations> ]}]})
public List<Users> find(String admin, String address, List<String> names, <insert parameters for 'school-college-company' combinations>);

我搜索了一种解决方案,可以提供具有以下参数的类型的对象列表:

class FilteringClass {
    String school;
    String college;
    String company;
} 

但没有运气。

我首先尝试将每个“学校”,“学院”和“公司”收集为单独的列表,并提供它们作为查询参数,但是显然,这并不完全正确,因为它将获取具有各种可能排列值的文档,而不是三者的独特结合。

请让我知道是否有上述需要的解决方案。 提前致谢。

完全按照问题中的说明创建一个类:

class SCCFilter {
String school;
String college;
String company;
} 

当来自用户的请求带有这些参数时,对于请求有效负载中的每个元素,我选择学校,学院和公司的值并将其存储在“过滤器”列表中。

(当然,可以对此进行优化以避免重复,但是作为上述问题的解决方案,它可以正常工作)

然后,我编写了以下查询:

@Query("{ '$and' : [ { 'admin' : ?0 , 'address' : ?1 } , { '$or' : [{'name': {'$in': ?2 }}, {'$or': ?3 }] }]}")
public List<Users> find(String admin, String address List<String> names, List<SCCFilter> filters)

这是我在运行时从日志中提取的最终查询,以(成功)在Mongo DB中进行测试:

{ "$and" : [ { "admin" : "admin1" , "address" : "addr1"} , { "$or" : [ { "name" : { "$in" : [ "Amy" , "Maya"]}} , { "$or" : [ {'school': 'S1', 'college': 'Col1', 'company': 'CompCop'}, {'school': 'S2', 'college': 'Col1', 'company': 'CompShop'}]}]}]}

比使用MongoTemplate更具可读性!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM