【问题标题】:Spring Boot and Mongo - how to query by nested propertySpring Boot 和 Mongo - 如何通过嵌套属性进行查询
【发布时间】:2020-05-08 01:38:32
【问题描述】:

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

我得到空列表:(

也许通过 Query 不可能做到这一点?

【问题讨论】:

  • 不幸的是我仍然没有解决我的问题。我想我尝试了所有选项......没有成功:(
  • 这些不适用于您的情况。您在 Product 类中使用 @DBRef 注释。请参阅这篇关于使用@DBRef 的帖子:Spring Mongo DB @DBREF。什么是数据库引用?请参阅 MongoDB 文档中的 DBRefs
  • 还是不行。我在 JSON 中添加了 "properties" : { "$ref" : "properties", "$id" : ObjectId("5df8dd2331ea7b4a9384335b") }。我的存储库看起来像 @Query(value = "{'properties.id': ?0 }") List findByPropertiesId(String propertiesId);
  • 我不知道是什么问题。 StackOverflow 和其他网站上都有很多相关的帖子。请尝试搜索“Spring MongoDB @DBRef”。仅作为建议:解决问题的一种方法是尝试在您自己上运行一个示例,这样您就可以从工作代码开始并进一步将其应用于您的情况。

标签: mongodb spring-boot mongorepository


【解决方案1】:
@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));
}

【讨论】:

  • 请花一点时间来编辑您的答案以包含一些解释,而不仅仅是一个代码块。这将帮助 OP 和未来的读者理解 为什么 而不仅仅是 如何。随着时间的推移,这些问题往往会变得更有用,并且更有可能得到支持。
猜你喜欢
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 2019-08-29
相关资源
最近更新 更多