mongodb Sping Boot 和Mongo -如何通过嵌套属性进行查询

ygya80vv  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(58)

我有以下问题-如何使用@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);
    }

我得到空列表:(
也许不可能通过查询来做到这一点?

jq6vz3qz

jq6vz3qz1#

@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));
}

相关问题