如何使用Spring JPA以及StartingWith查询MongoDB

huangapple go评论91阅读模式
英文:

How to Query MongoDB using Spring JPA along with StartingWIth

问题

我的MongoDB文档中,_id 被定义为字符串。_id 的典型值如下:

  • abc#1234
  • abc#2345
  • aby#5678
  • abx#123

我想要进行一个以 abc# 为前缀的查询,以返回 abc#1234abc#2345(考虑到Mongo中 _id 已排序,我认为前缀查询会更有效,比二级索引更有效,请纠正我如果我错了)。

我尝试了以下代码,但返回的列表大小为0:

@Repository
public interface DBEntityRespository extends MongoRepository<DBEntity, String> {
    public List<DBEntity> findByIdStartingWith(String id);
}

实体类定义如下:

@Document(collection = "someDBEntity")
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DBEntity {

    @Id
    @JsonProperty("_id")
    private String id;
    // ...
    // ...
    // ...
}

我以以下方式调用仓库:

@GetMapping("/v1/x")
public String hi(){
    List<DBEntity> list = repo.findByIdStartingWith("abc"); // 尝试使用^abc,/abc/,abc.* 但没有成功
    System.out.println(list.size()); // 返回列表大小为0
    return "success";
}

有关如何解决此问题并返回以 abc 为前缀的完整文档的想法吗?

英文:

My mongo db has documents with _id defined as string. Typical values for _id s are

  • abc#1234
  • abc#2345
  • aby#5678.
  • abx#123

I want to do a prefix query around abc# to return abc#1234 abc#2345 (given that _id are sorted in Mongo, I think the prefix query will be efficient --more efficient than 2ndry indexes --Please correct me if I am wrong)

I tried the below and it returned a list of size 0.

@Repository
public interface DBEntityRespository  extends MongoRepository&lt;DBEntity, String&gt; {
    public List&lt;DBEntity&gt; findByIdStartingWith(String id);
}

entity is defined as...

@Document(collection = &quot;someDBEntity&quot;)
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DBEntity {

    @Id
    @JsonProperty(&quot;_id&quot;)
    private String id;
...
...
...
}

I am calling the repository as follows

   @GetMapping(&quot;/v1/x&quot;)
    public String hi(){
        List&lt;DBEntity&gt; list = repo.findByIdStartingWith(&quot;abc&quot;);// &lt;&lt; tried with ^abc , /abc/, abc.* but no luck
        System.out.println(list.size() ); // &lt;&lt; returns list of size 0
        return &quot;success&quot;;
    }

Any thoughts on how to get the issue fixed? and return the full documents matching the prefix abc ??

答案1

得分: 2

@Query("{'id': { $regex: '^?0', $options: 'i' } }")
public List findByIdStartingWith(String id);

英文:

You can try this query

@Query(&quot;{ &#39;id&#39; : { $regex: &#39;^?0&#39;, $options: &#39;i&#39; } }&quot;)
public List&lt;DBEntity&gt; findByIdStartingWith(String id);

huangapple
  • 本文由 发表于 2023年7月3日 22:29:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定