英文:
How to Query MongoDB using Spring JPA along with StartingWIth
问题
我的MongoDB文档中,_id
被定义为字符串。_id
的典型值如下:
abc#1234
abc#2345
aby#5678
abx#123
我想要进行一个以 abc#
为前缀的查询,以返回 abc#1234
和 abc#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<DBEntity, String> {
public List<DBEntity> findByIdStartingWith(String id);
}
entity is defined as...
@Document(collection = "someDBEntity")
@Data
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DBEntity {
@Id
@JsonProperty("_id")
private String id;
...
...
...
}
I am calling the repository as follows
@GetMapping("/v1/x")
public String hi(){
List<DBEntity> list = repo.findByIdStartingWith("abc");// << tried with ^abc , /abc/, abc.* but no luck
System.out.println(list.size() ); // << returns list of size 0
return "success";
}
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
英文:
You can try this query
@Query("{ 'id' : { $regex: '^?0', $options: 'i' } }")
public List<DBEntity> findByIdStartingWith(String id);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论