使用 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. 文件必须具有 "name" 作为 ["Amy"、"Maya"] 之一,或者它们必须具有以下学校-学院-公司组合之一-

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

这些值和此类组合的数量可能因动态传入的 Web 请求中提供的内容而异。

第二点是我在 java 中使用 @Query 注释将基于 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;
} 

但没有运气。

我开始尝试收集每个 "school"、"college" 和 "company" 作为单独的列表,并将它们作为查询参数提供,但显然,这不太正确,因为它会获取包含值的所有可能排列的文档,而不是三者的唯一组合。

如果有任何我需要的解决方案,请告诉我,如上所述。提前致谢。

创建了一个 class 与问题中提到的完全相同:

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

当请求来自带有这些参数的用户时,对于请求负载中的每个元素,我选择学校、学院和公司的值并将它们存储在 'filters' 的列表中。

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

然后我写了下面的查询:

@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 数据库中测试(成功):

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

比使用 Mongo模板更具可读性!