问题描述
在此应用程序中,我还插入了一项功能,该功能使我可以在数据库存储库的对象内查找特定项目。为此,我使用了mongo模板。 我的存储库中的每个对象都包含以下各项:
[
{
"id": "5f759b198dfb247ccd6280b2","name": "Probando lo que cree","text": "Enrique Gordon","description": "Un poquito de todo ","images": [
"R0lGODlhLAEsAff"
],"videos": [
"AAAAIGZ0eXBpc29"
],"date": null,"allComments": null
},{
"id": "5f759d2b8dfb247ccd6280ba","description": "Algo nuevo",{
"id": "5f75a5e2275d7d34914d2d98","name": "Zamorano","text": "Zamorano","description": "Zamorano","images": [
"iVBORw0KGgoAAAA","/9j/4T/+RXhpZgA"
],"allComments": null
}
]
因此请记住,我在存储库中初始化了一个函数,该函数将返回一个包含以下内容的查询:描述,文本和名称
REPOSITORY
public List<Post> searchPosts(String search){
return mongoTemplate.aggregate(Aggregation.newAggregation(
Aggregation.match(new Criteria().orOperator(
Criteria.where("text").regex(search),Criteria.where("description").regex(search),Criteria.where("name").regex(search),))
),"Post",Post.class).getMappedResults();
}
*The post is the class already initilized with getters and setters,having in mind the concepts text,name,and description too
然后在我的终点,请记住条件是我将传递的所有条件作为路径变量传递给终点
CONTROLLER
@GetMapping("/post/{search}/search")
public List<Post> getSearchedPosts(@PathVariable ("search") String search){
return postRepository.searchPosts(search);
}
但是,当我带着邮递员来测试流程时,如果有任何共鸣,它都会带给我所有对象,但不会带给我所要查询的对象。
解决方法
您不需要为此进行汇总。
尝试一下-希望它能起作用。
Query query= new Query(
new Criteria()
.orOperator(
Criteria.where("text").regex(search),Criteria.where("description").regex(search),Criteria.where("name").regex(search)
)
);
return mongoTemplate.find(query,Post.class);
我在本地环境中使用您提供的示例文档进行了尝试。我使用Zamorano
作为搜索字符串。我只得到一个结果。这是我的代码-
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@AllArgsConstructor
public class SOController {
@Autowired
MongoTemplate mongoTemplate;
@GetMapping("/post/{search}/search")
public List<Post> getSearchedPosts(@PathVariable("search") String search) {
Query query = new Query(
new Criteria()
.orOperator(
Criteria.where("text").regex(search),Criteria.where("name").regex(search)
)
);
return mongoTemplate.find(query,Post.class,"so");
}
}
这是邮递员的img-
PS-确保您的导入正确无误。