Spring Boot和Mongo-如何通过嵌套属性查询

我有以下问题-如何使用@Query通过嵌套属性查询?

我的产品类(位于Mongo中的文档):

@Document(collection = "products")
public class Product {

    @Id
    private String id;

    @DBRef
    private ProductProperties properties;

它在Mongo中的外观如何

{
    "_id" : ObjectId("5d5e78d20e8e3d0006079a84"),"companyId" : "1234","properties" : {
        "$ref" : "properties","$id" : ObjectId("5df8dd2331ea7b4a9384335b")
    },"calendar" : [ 
        {
            "startDate" : ISODate("2019-09-04T22:00:00.000Z"),"endDate" : ISODate("2019-09-09T22:00:00.000Z")
        }
    ],"_class" : "org.abc.def"
}

ProductProperties类(Mongo中的文档):

    @Document(collection = "product_properties")
    public class ProductProperties {
        @Id
        private String id;
(...)

它在Mongo中的外观如何

   {
    "_id" : ObjectId("5df8dd2331ea7b4a9384335b"),"brand" : "offer Brand_1","model" : "offer model_1","modelNumber" : "offer model number_1","size" : {
    ...
}

我的Spring存储库:

public interface ProductRepository extends MongoRepository<Product,String> {

    @Query("{'properties.id': ?0 }")
    List<Product> findByPropertiesId(String propertiesId);

我也尝试过:

List<Product> findByProperties_id(String propertiesId)

@Query("{'properties.$id': ?0 }")
        List<Product> findByPropertiesId(ObjectId propertiesId);

但没有成功。你知道怎么了吗?

当我调用时:

public List<Product> findProductsByPropertiesId(String properties) {
        if (properties == null) {
            throw new IllegalArgumentException("onFind: propertiesId should not be null.");
        }
        return productRepository.findByProperties_Id(properties);
    } 

我得到一个空列表:(

也许不可能通过查询来做到这一点?

wangch0808 回答:Spring Boot和Mongo-如何通过嵌套属性查询

@Query("{'properties.$id': ?0 }")
List<Product> findByPropertiesId(ObjectId propertiesId);


public List<Product> findProductsByPropertiesId(String properties) {
    if (properties == null) {
        throw new IllegalArgumentException("onFind: propertiesId should not be null.");
    }
    return productRepository.findByPropertiesId(new ObjectId(properties));
}
本文链接:https://www.f2er.com/2735663.html

大家都在问