Java Spring Data MongoDB-使用@Query或MongoTemplate和$elemMatch从嵌套数组中仅返回一个元素

Java Spring Data MongoDB-使用@Query或MongoTemplate和$elemMatch从嵌套数组中仅返回一个元素,java,spring,mongodb,spring-data,spring-data-mongodb,Java,Spring,Mongodb,Spring Data,Spring Data Mongodb,我的模型由一组(汽车)模型组成,其中包含一组嵌套的可用燃料类型(“柴油”、“汽油”、“混合动力”)。每种燃料都有另一个嵌套的可用门集合 例如: { _id : 'Ford Focus' , fuels : [ {_id : "Diesel" : "doors" : [2 , 3]} , {_id: "Gasoline" , doors : [2, 3, 4, 5] } ] } 如果我想让某一型号和燃料类型的车门可用,我可以执行: db.models.find( {"_id" : "Ford

我的模型由一组(汽车)模型组成,其中包含一组嵌套的可用燃料类型(“柴油”、“汽油”、“混合动力”)。每种燃料都有另一个嵌套的可用门集合

例如:

{ _id : 'Ford Focus' , fuels : [ {_id : "Diesel" : "doors" : [2 , 3]} , {_id: "Gasoline" , doors :  [2, 3, 4, 5] } ] } 
如果我想让某一型号和燃料类型的车门可用,我可以执行:

db.models.find( {"_id" : "Ford Focus" , "fuels._id" : "Diesel"}  , { 'fuels' : {$elemMatch: {_id: "Diesel"}  } })
如何将其转换为Spring数据存储库中的@Query方法

@Query(value="{ 'id' : ?0 , 'fuel' : ?1 }")
public Model findDoors(Integer model, String fuel);
上面的实现返回一个带有嵌套数组的文档,该数组包含所有类型的燃料,而不仅仅是作为参数传递的燃料。在Spring数据存储库中,哪里可以放置$elemMatch投影

@Query(value="{ 'id' : ?0 , 'fuel' : ?1 }")
public Model findDoors(Integer model, String fuel);
更新:经过一些研究,我尝试使用自定义存储库MongoTemplate和BasicQuery类来完成它,如下所示

在这种情况下,当调用
PropertyPath
的构造函数时,我得到一个异常,因为它试图访问Model.class(???)中名为$elemMatch的字段

原因:java.lang.IllegalAccessError
位于org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
位于org.springframework.data.mapping.PropertyReferenceException。(PropertyReferenceException.java:59)
位于org.springframework.data.mapping.PropertyPath.(PropertyPath.java:75)

您使用的是哪个版本的spring framework?Spring Data Golsing版本至少需要
Spring 4.1.7
或更高版本。嗨,Christoph,我使用的是Spring 4.1.6.release,升级后我刚刚测试过它,它工作得很好,谢谢!!
Caused by: java.lang.IllegalAccessError
at org.springframework.data.mapping.PropertyReferenceException.detectPotentialMatches(PropertyReferenceException.java:134)
at org.springframework.data.mapping.PropertyReferenceException.<init>(PropertyReferenceException.java:59)
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75)